Reputation: 4203
I am using C. I am having issues with using pointers for the fscanf function. When I try to do:
int *x;
/* ... */
fscanf(file, "%d", x[i]);
My compiler gives me a warning saying "format argument is not a pointer" and the code just doesn't run (I get a message saying "Water.exe has stopped working"). If I replace x with *x, it just doesn't compile... Is this just a syntax issue?
Upvotes: 2
Views: 7791
Reputation: 532435
You need to allocate some space for the results.
int *x; // declares x
x = malloc( 600000 * sizeof(int) ) // and allocates space for it
for (int i = 0; i < 600000; ++i ) {
fscanf(file, "%d", &x[i] ); // read into ith element of x
}
Upvotes: 8
Reputation: 75389
If you want to read a single integer, do this:
int x;
fscanf(file, "%d", &x );
If you want, you could do this to read a single integer in a dynamically-allocated variable:
int *x = malloc(sizeof(int));
fscanf(file, "%d", x );
If you want an array of integers, do this:
int *x = malloc(sizeof(int) * DESIRED_ARRAY_SIZE);
fscanf(file, "%d", &x[i] );
%d
expects a pointer to an int
, but x[i]
is an int
, so you need to take the address of your list element using the address-of operator (unary &
).
Upvotes: 12