2017-05-02 19 views
-5

有什麼區別讀取數&a,只是a是什麼用途與和之間差異

int main(int argc, char** argv) { 
    int a; 

    printf("A:"); 
    scanf("%d",&a); 
    printf("Address:%p\n",&a); 
    printf("value A:%d",a); 

    return (0); 
} 

有時候,我看到那裏不是讀取變量,他們讀給我知道的地址碼的變量只是內存但不一樣?我可以做到這兩個?或者有時我必須特別使用其中之一?

+1

傳遞'&了'意味着你逝去的'了'地址' scanf()的'。只要傳遞'a'就意味着'a'是一個指向'int'的指針。請注意,'scanf()'需要某種地址。 – Logan

+4

當使用'scanf'時,您應該_always_使用指針來讀取變量的數據。在C中,每個參數都通過值傳遞,如果定義了使用'%d'選項將值傳遞給'scanf()'的行爲,則會創建'a'的副本並寫入該副本,這對您沒用因爲您無法訪問該數據。 – George

+0

['scanf'](http://en.cppreference.com/w/c/io/scanf)和['printf'](http://en.cppreference.com/w/c/)的文檔io/fprintf)指定每個對於與格式說明符匹配的相應參數所期望的要求。在該文檔中所述的情況下,需要使用地址運算符'&'。 – WhozCraig

回答

2

在C中,如果你想要一個函數來修改一個對象的(如ascanf呼叫)中的值,則必須一個指針傳遞給該對象。指針是任何表達式,其值是內存中對象的位置

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 
+0

感謝您的幫助!我想我明白了,我有點迷惑 –

相關問題