Reputation: 38
I am trying to read data from a file to store his first n elements in an array. The data is an integer sequence:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
When I check the content of the array, I don't find the correct values, it seems like it is saveing the address(?) of the correct values?
Here is my piece of code:
FILE* ifp;
ifp = fopen ("input.txt", "r");
int n = 10;
int* readbuf;
readbuf = (int *) malloc (n * sizeof(int));
for (int i=0; i<n; i++){
int j = 0;
fscanf (ifp, "%d", &j);
j = readbuf[i];
printf ("\n j = %d and readbuf = %d", j, readbuf[i]);
}
fclose(ifp);
Would the code be different if the input file contains following sequence:
0
1
2
3
...
Upvotes: 0
Views: 2098
Reputation: 2472
This should fix it :
readbuf[i] = j;
instead of
j = readbuf[i];
Upvotes: 3