在C中,如果你想要一個函數來修改一個對象的(如a
在scanf
呼叫)中的值,則必須一個指針傳遞給該對象。指針是任何表達式,其值是內存中對象的位置。
scanf("%d", &a); // write an integer value to a
您可以創建服務大致相同目的的指針變量:
int a;
int *p = &a; // the object p stores the location of a
// p points to a
scanf("%d", p); // also writes an integer value to a through the pointer p
// note no & here because p is already a pointer type
如果你只是想通過在這種情況下,指針a
通過使用一元&
運營商獲得對象的值的函數,你不會使用&
操作:
printf("%d", a); // write the value stored in a to standard output,
// formatted as a decimal integer
如果你有一個指針,你想要的對事物價值的指針指向,你會使用一元*
操作:
printf("%d", *p); // write the value stored in a to standard output,
// going through the pointer p
總之,
p == &a // int * == int *
*p == a // int == int
傳遞'&了'意味着你逝去的'了'地址' scanf()的'。只要傳遞'a'就意味着'a'是一個指向'int'的指針。請注意,'scanf()'需要某種地址。 – Logan
當使用'scanf'時,您應該_always_使用指針來讀取變量的數據。在C中,每個參數都通過值傳遞,如果定義了使用'%d'選項將值傳遞給'scanf()'的行爲,則會創建'a'的副本並寫入該副本,這對您沒用因爲您無法訪問該數據。 – George
['scanf'](http://en.cppreference.com/w/c/io/scanf)和['printf'](http://en.cppreference.com/w/c/)的文檔io/fprintf)指定每個對於與格式說明符匹配的相應參數所期望的要求。在該文檔中所述的情況下,需要使用地址運算符'&'。 – WhozCraig