Code:
#include <stdio.h>#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
int temp;
int *arr;
int counter = 0;
fp = fopen("vals.txt", "r");
while (fscanf(fp, "%d", &temp) != EOF) {
if (arr == NULL) {
arr = (int *) malloc(sizeof(int));
arr[0] = &temp;
counter++;
} else {
arr = (int *) realloc(arr, (counter + 1) * sizeof(int));
arr[counter++] = &temp;
}
}
fclose(fp);
free(arr);
return 0;
}
I tried but it fails with segmentation error on the line after realloc. Any idea why this would happen?