Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question regarding pointers in fscanf

Tags:

c

pointers

scanf

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?

like image 817
wolfPack88 Avatar asked Apr 26 '26 11:04

wolfPack88


1 Answers

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 &).

like image 121
Chris Lutz Avatar answered Apr 29 '26 04:04

Chris Lutz