0

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
...
1
  • To read a line you could use fgets. There is a example too. Commented Mar 3, 2014 at 16:47

1 Answer 1

3

This should fix it :

readbuf[i] = j;

instead of

j = readbuf[i];
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thanks! Now I look at it and all I can think is /facepalm
Don't let that bring you down. It happens even to the best programmers sometimes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.