You are not handling input error. If scanf fails to read, your program has undefined behaviour which may result in it quickly eating up all your memory and then crashing.
It's also advised to handle realloc failure, and also not reallocate every single time around.
Putting this all together, and also avoiding adding -1 to the array, it might look something like this:
/* values are read into this buffer */
int size = 16, count = 0;
int *a = malloc(size * sizeof(int));
/* loop control variables */
int done = 0;
int error = 0;
/* temporary variables */
int val, new_size, *new_a;
while( !done )
{
/* double the buffer size when required */
if( count == size )
{
new_size = size * 2;
new_a = realloc(a, new_size * sizeof(*a));
if( !new_a ) {
perror("Realloc failed");
error = 1;
break;
} else {
a = new_a;
size = new_size;
}
}
/* read value and finish on input error or if user enters -1 */
if( 1 != scanf("%d", &val) || val == -1 ) {
done = 1;
} else {
a[count++] = val;
}
}
a[i-1]to be wheniis 0?a[i-1]problem you can change the loop fromwhiletodo/while.