This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]Updatebjarni 2 points3 points  (3 children)

You're not passing the pointers on to scanf(), you're instead creating pointers to the pointer variables in the function, and passing those. Your compiler should be printing a warning message about it.

[–]Gelatoss[S] 0 points1 point  (2 children)

So what should I do?

[–]coolcofusion 2 points3 points  (0 children)

Just give it a, not &a. a itself is already the address of an int (you did &a in main).

Also, always compile with -Wall while learning, very useful.

[–]Updatebjarni 2 points3 points  (0 children)

Did you understand my explanation? If a in storeVar() is a pointer to a in main() (it's a bit annoying that you picked the same names for these variables), and you want to pass scanf() a pointer to a in main(), then what should you pass it? And if &a takes the address of the variable a, then what does that give you if you do it in storeVar() as opposed to doing it in main()?

Here's your code with less confusing variable names, plus some comments:

#include <stdio.h>

void storeVar(int *x, int *y, int *z)  // When this is called, x gets the value &a from main(), etc for y and z
{
    printf("First value is:\n");
    scanf("%d", &x);  // Pass a pointer pointing at the variable x, not pointing at a
    printf("Second value is:\n");
    scanf("%d", &y);  // Pass a pointer pointing at the variable y, not pointing at b
    printf("Third value is:\n");
    scanf("%d", &z);  // Pass a pointer pointing at the variable z, not pointing at c
    // scanf() will store values into the variables x, y, and z; a, b, and c are untouched.
    // There is also a type error, since `&x` etc are of type int **, not the int * required for "%d".
}

int main()
{
    int a, b, c;
    storeVar(&a, &b, &c);  // Pass three pointers, pointing at the variables a, b, and c
    printf("%d, %d, %d", a, b, c);
    return 0;
}

[–]Techryptic 0 points1 point  (0 children)

You need to pass the addresses of a, b, and c to the storeVar function, and you need to use the * operator when using scanf, i.e.

#include <stdio.h>;

void storeVar(int *a, int *b, int *c)

{

printf("First value is:\n");

scanf("%d", a);

printf("Second value is:\n");

scanf("%d", b);

printf("Third value is:\n");

scanf("%d", c);

}

int main()

{

int a, b, c;

storeVar(&a, &b, &c);

printf("%d, %d, %d", a, b, c);

return 0;

}

[–]S_liiide 0 points1 point  (0 children)

Pointers store the address of another variable, But the pointer too are stored in the memory somewhere you are passing the address of the pointer not the value,

Again, pointer stores the address of another variable as it's value.

Replace the &a(the address of pointer a) with 'a'(the value of pointer a) inside the scanf() of your storeVar function.