tags:

views:

99

answers:

4

Why do this work?

    int *var;

while(scanf("%d", &var) && *var != 0)
        printf("%d \n", var);

While this does not?

    int *var;

while(scanf("%d", &var) && var != 0)
    printf("%d \n", var);

Doesn't * (dereference operator) give you the value pointed by the pointer? So why does *var != 0 crash the program, while var != 0 does not?


This worked:

int* var = malloc(sizeof(int));

while(scanf("%d", var) && *var != 0)
    printf("%d \n", *var);

Doing a refresher course on C, glad I did it.

I realized that scanf(&var) is for regular variables, while scanf(var) is for pointers. But completely forgot about the memory, thank you!

+3  A: 

I'm not sure what you mean by "works," but the first one is wrong because you are taking what var points to and comparing it to zero in the first example, and since var has been initialized to what the user entered, what var points to is not likely to be a valid place.

*var != 0

This takes the value pointed to by the user-defined var.

Note that in the scanf, you are scanning an integer into int **, rather than int *, and printf is using %d to print a pointer, rather than an integer.

Things may seem to work or fail when you do undefined things for various reasons. You should understand why the code you're writing is correct, rather than putting down some code, and changing it until it works.

WhirlWind
It's not that var hasn't been initialized, so much as it has been initialized to the number the user entered, so it's very unlikely to point at a valid memory address.
sepp2k
sepp2k my mistake -- updated.
WhirlWind
A: 

You pass an int* to sscanf, not int**. Either remove the * from the first declaration or initialize it to something like malloc(sizeof(int)) and remove the & from the sscanf call.

bmargulies
A: 
sbi
A: 
(1) int i; // reserves an integer
(2) scanf("%d",&i); // writes to the address of i
(3) int *var; // is a pointer pointing to some unpredictable place 
(4) int *var = &i; // would point exactly to the adress of i
(5) scanf("%d",var) // would be the same as (2)
stacker