I am trying to get string of numbers and put it inside an int
array.
I have no idea how many numbers I am going to get so I need to use dynamic allocation.
I created an array by using malloc
and tried to resize it by +1
every time inside the loop.
This is my code
void main()
{
char *s;
int *polyNums;
int count = 0;
char *token;
s = gets();
polyNums = (int *)malloc(sizeof(int));
if (polyNums == NULL)
{
printf("Could not allocate required memory\n");
exit(1);
}
token = strtok(s, " ");
while (token != NULL)
{
polyNums[count] = *token - '0';
count++;
polyNums = realloc(polyNums, count+1);
token = strtok(NULL, " ");
}
}
My problem is that every time it's doing realloc
, all the saved numbers are gone, if my string is "1 2 3"
so in loop 1 the polyNums[0]
is 1
, but I am loosing it in loop 2 after reallocating. Can some one please tell me where I went wrong?