Why don't I need ampersands with the scanf? (I

2019-07-24 10:42发布

void getnums(int *a, int *b);

int main()   
{  
    int a;
    int b;
    int c;
    getnums(&a,&b);
    c = a + b;
    printf("a + b = %d\n", c);
    return 0;  
}

void getnums(int *a, int *b)
{ 
    printf("a:? ");
    scanf("%d", a);
    printf("b:? ");
    scanf("%d", b);
}

Why don't I need ampersands before the a and b in the scanfs? (The code currently works.)

2条回答
2楼-- · 2019-07-24 11:28

Because scanf takes pointers as its arguments (so that it knows what variable to modify), and a and b are already pointers.

查看更多
女痞
3楼-- · 2019-07-24 11:28

Whenever we scan some input it needs a memory location(i.e. address) to store that value, for simple variables we have to use & - ampersand - to provide that address.

Here, in function getnums, a and b are pointers so they will already contain address, so no need to write & to give the address.

查看更多
登录 后发表回答