I'm trying to use realloc to add an element to an array after inputting characters. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, j, k;
int a = 1;
int* array = (int*) malloc(sizeof(int) * a);
int* temp;
for(i = 0;;i++)
{
scanf("%d", &j);
temp = realloc(array, (a + 1) * sizeof(int));
temp[i] = j;
if(getchar())
break;
}
for(k=0; k <= a; k++)
{
printf("%d", temp[k]);
}
}
When I run this little program, and if I enter for exemple : 2 3 4 it displays me: 20; I know that memory hasn't been allocated properly, but I can't figure out the issue. Thanks in advance.
Firstly:
int* array = (int*) malloc(sizeof(int) * a);
int* temp = array;
and
temp = realloc(temp, (a + 1) * sizeof(int));
because after call 'realloc' pointer passed as first argument may becomes invalid.
And of course 'realloc' called with second parameter equal 2 always.
By the way 'scanf' stops read your input string after first non-digit character. Read documentation for correctly usage functions. For example about scanf() or realloc().