Question about pointers in fscanf
I am using C. I am having problems using pointers for fscanf function. When I try to do:
int *x;
/* ... */
fscanf(file, "%d", x[i]);
My compiler gives me a warning that "the format argument is not a pointer" and the code just won't run (I get a message that "Water.exe has stopped working"). If I replace x with * x it just doesn't compile ... Is it just a syntax problem?
source to share
If you want to read a single integer, do this:
int x;
fscanf(file, "%d", &x );
If you want, you can do this to read a single integer into 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 int
, but x[i]
is int
, so you need to take the address of your list item using the address-operator (unary &
).
source to share