tags:

views:

206

answers:

2

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?

+8  A: 

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
}
tvanfosson
I've tried to allocate space by doing the following:x = (int *) calloc(600000, sizeof(int));However, that still doesn't work...
wolfPack88
What you show is the proper way to do it, this isn't but goes to illustrate what is the OP doing wrong: int *x; x = malloc(sizeof(int)); fscanf(file, "%d", x); would work.
Vinko Vrsalovic
Given that the OP is trying to read values into `x[i]`, I think he wants an array, rather than a single `int`.
Chris Lutz
@Chris -- the question changed out from under my answer.
tvanfosson
@Vinko -- I had actually typed that in as an alternative, but omitted it to try and avoid confusion.
tvanfosson
Yeah, sorry about that. I had made a typo. I realized that after reading your answer. Thanks anyways, though.
wolfPack88
tvanfosson
Updated with example using array.
tvanfosson
+5  A: 

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

Chris Lutz
+1 for including a sample demonstrating the address of an array element which seems to me to be the source of the OP's confusion.
RBerteig