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?

+2


source to share


2 answers


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 &

).

+11


source


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
}

      

+8


source







All Articles