I'm trying to read ints from stdin, but i don't know the length. I tried this but I have no idea why it doesn't work
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr = (int *) malloc(sizeof(int));
int sizeCounter = 0;
int tmp = 0;
while(scanf("%d", &tmp) != EOF)
{
arr = (int *) realloc(arr, sizeof(arr)+sizeof(int));
arr[sizeCounter] = tmp;
sizeCounter++;
}
}
Error - realloc(): invalid pointer: 0xb76d8000 *
This line is wrong.
arr = (int *) realloc(arr, sizeof(arr)+sizeof(int));
sizeof(arr)+sizeof(int)
is a constant. It is equal to sizeof(int*)+sizeof(int)
.
What you need is:
arr = (int *) realloc(arr, (sizeCounter+1)*sizeof(int));