2015-11-29 38 views
-2

你能解釋一下下面的代碼,勘定指針,地址運營商和取消引用指針用C

int main() { 
    int value = 2; 
    int *ptrWithAmpersand = &value; 
    int *ptrWithoutAmpersand = value; 
    //printf("%d", *ptrWithoutAmpersand); 1) Why Runtime error. 
    printf("Pointer with & --> %d\n", *ptrWithAmpersand); 
    printf("Pointer withOUT & and * --> %d\n", ptrWithoutAmpersand); //2) Why this works??!! 
    getch(); 
} 

代碼

  1. 爲什麼運行時錯誤作爲評論?
  2. 爲什麼這項作品?

輸出是

Pointer with & --> 2 
Pointer withOUT & and * --> 2 

回答

1

在行

int *ptrWithAmpersand = &value; 

要創建一個指向int,並給它分配變量value地址。到現在爲止還挺好。

在線路

int *ptrWithoutAmpersand = value; 

要創建一個指向int並分配內容(2)給它的可變value。這導致幾個問題:

  1. 您正試圖int類型的值賦給int *類型的變量,這是不兼容的類型;編譯器應該至少發出「不兼容的類型分配」(全部警告上轉),警告或類似的東西

  2. 在您的系統,2是不是有效的對象的地址,因此運行時錯誤時嘗試解除引用ptrWithoutAmpersand

在代碼中有其他幾個問題。您不應該使用%d轉換說明符來打印指針值;爲此目的總是使用%p

這是你的代碼的輕微重寫使得一些事情更清楚一點:

#include <stdio.h> 

int main() { 
    int value = 2; 
    int *ptrWithAmpersand = &value; 
    int *ptrWithoutAmpersand = value; // throws a warning in gcc; you should not do this 

    printf("value of expression \"value\" = %d\n", value); 
    printf("value of expression \"&value\" = %p\n", (void *) &value); 
    printf("value of expression \"ptrWithAmpersand\" = %p\n", (void *) ptrWithAmpersand); 
    printf("value of expression \"*ptrWithAmpersand\" = %d\n", *ptrWithAmpersand); 
    printf("value of expression \"ptrWithoutAmpersand\" = %p\n", (void *) ptrWithoutAmpersand); 

    return 0; 
} 

這裏是代碼的輸出:

value of expression "value" = 2 
value of expression "&value" = 0x7ffecb63cf44 
value of expression "ptrWithAmpersand" = 0x7ffecb63cf44 
value of expression "*ptrWithAmpersand" = 2 
value of expression "ptrWithoutAmpersand" = 0x2 

注意指針表達式是如何打印出與整數表達式。

簡而言之:

*ptrWithAmpersand == value == 2  type == int 
ptrWithAmpersand == &value    type == int * 
ptrWithoutAmpersand == value == 2  mismatched types int * and int 
+0

這是一個非常詳細的解釋。幫助我很多!謝謝! – user859385

1

在:

int *ptrWithAmpersand = &value; 
printf("Pointer with & --> %d\n", *ptrWithAmpersand); 

您正確的地址分配給指針,並在printf你正確地解引用它來打印一個int與%d參數。

在:

int *ptrWithoutAmpersand = value; 
printf("Pointer withOUT & and * --> %d\n", ptrWithoutAmpersand); 

您incorectly分配一個整數值的指針,而是因爲在printf你不取消引用它,它就會被打印成一份int%d參數。這隻會導致一個問題(UB),如果sizeof(int *) != sizeof(int)

在:

int *ptrWithoutAmpersand = value; 
printf("%d", *ptrWithoutAmpersand); 

,因爲你提領指向的內存地址2,這是不是你的,所以系統會中止程序的指針,你得到一個運行時錯誤。