I wrote this function for an assignment. It utilizes dynamic memory, which grows and shrinks as needed. I wrote it like this at first:
int user_input (int * array, int intSize)
{
printf("Please enter any number of integers (80 characters per string max), enter an empty string to signal input completion\n\n");
int i = 0, j = 0;
int arrayMax = MAXARRAY;
char input[80];
char * save;
while (input[0] != '\0')
{
if (j == arrayMax)
{
arrayMax *= 2;
realloc_data_up(array, intSize, arrayMax);
}
printf("->");
i = 0;
while(i < 80 && (input[i] = getchar())!= '\n')
{
i++;
}
input[i] = '\0';
save = strtok(input, " ");
while(save != '\0')
{
array[j] = atoi(save);
save = strtok(NULL, " ");
j++;
}
}
realloc_data_down(array, j, intSize);
return j;
}
And it works fine. I tried changing it up to this:
int user_input (int * array, int intSize)
{
printf("Please enter any number of integers (80 characters per string max), enter an empty string to signal input completion\n\n");
int i = 0, j = 0;
int arrayMax = MAXARRAY;
char input[80];
char * save;
while (input[0] != '\0')
{
printf("->");
i = 0;
while(i < 80 && (input[i] = getchar())!= '\n')
{
i++;
}
input[i] = '\0';
save = strtok(input, " ");
while(save != '\0')
{
if (j == arrayMax)
{
arrayMax *= 2;
realloc_data_up(array, intSize, arrayMax);
}
array[j] = atoi(save);
save = strtok(NULL, " ");
j++;
}
}
realloc_data_down(array, j, intSize);
return j;
}
And it gives me an error for pointer not being allocated. Just wondering how the first code works when the second doesnt.
Thanks.