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

夙愿已清 提交于 2020-01-15 12:35:29

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/10521463/why-dont-i-need-ampersands-with-the-scanf-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!