2013-11-01 84 views
-2

請你解釋一下p =(int *)(p + 1)行的輸出。爲什麼輸出是這樣的?

#include <stdio.h> 


int main() 
{ 
    int a[3]={2,3,4}; 
    char *p; 

    p=a; 
    p=(char *)((int*)(p)); 
    printf("%d\n",*p); 
    p=(int *)(p+1); 
    printf("%d",*p); 

    return 0; 
} 
+2

因爲你沒有格式化你的代碼。 – 2013-11-01 06:40:43

+0

它給出了2 0如何在輸出中出現0。 – user2515155

+0

也許你應該告訴我們你期望得到什麼,爲什麼你認爲'0'不應該在那裏? –

回答

4

這個p=(int *)(p+1);只會增加一個字節的地址,因爲p是一個字符指針。 它應該是p=(int *)(p+4);來訪問下一個整數元素。

+1

它也取決於你的編譯器,你的編譯器把整數看作4字節還是2字節,還有字符的大小。無論如何,上述邏輯是正確的,你應該相應增加。 – anon

+0

@nishu:確切地說。 –

+0

@ user1940987不,不完全是「完全」。這種不兼容的指針類型的技巧違反了嚴格的別名規則,因此它會調用未定義的行爲。 – 2013-11-01 07:36:42

2

嗯......讓我們來看看這一步一步的,好嗎:

#include <stdio.h> 


int main() 
{ 
    /* OK, here we have an array of 3 integers. That's fine. Each 
    * of these is sizeof(int) bytes, typically 4 bytes. So this 
    * array would typically be 12 bytes long. 
    */ 
    int a[3]={2,3,4}; 

    /* And here we have a pointer to a character. A character will 
    * have a size of 1 byte. */ 
    char *p; 

    /* Uhm... this is suspicious. Remember, p is a pointer to 
    * a character, but a points to an integer. You can't mix 
    * potatoes and tomatoes (or things that are 4 bytes and things 
    * which are 1 byte. That's asking for trouble!) 
    */ 
    p=a; 

    /* Well... this is slightly pointless. And ugly. What do you 
    * think this code does? If you said "nothing" you'd be right. 
    */ 
    p=(char *)((int*)(p)); 

    /* OK... so here you dereference the pointer p, and get 
    * back a single *character* (since p is a pointer to a 
    * character) and print that character as an integer. 
    */ 
    printf("%d\n",*p); 

    /* Now you increment p by one element. Since p is a 
    * pointer to a character, you are actually incrementing 
    * the address by one, since the size of a character is 
    * 1. 
    * 
    * But p was made to point to an array of integers and 
    * integers are larger than 1 byte. Typically, they are 
    * 4 bytes long. So now you're pointing 1 byte into an 
    * integer. 
    */ 
    p=(int *)(p+1); 

    /* And now you print whatever *CHARACTER* is at that address 
    * as an integer. 
    */ 
    printf("%d",*p); 

    return 0; 
} 

代碼的註釋這個版本應該幫助你找出發生了什麼。如果您需要更多幫助,請考慮這個概念圖,它顯示您在最後一個printf之前的內存。每一對[]代表一個字節,箭頭代表指針:

[2][0][0][0][3][0][0][0][4][0][0][0] 
^^ 
a--' | 
p-----' 
0

是......你知道的。

1.如果p是一個指針,指向字符,P + 1表示地址+ 1

2.如果p是一個指針指向一個整數,p 1表示地址+ 4

如果的地址是像下面

02 00 00 00 03 00 00 00 00 04 00 00 00

p=(char *)p;這意味着,現在p是一個指向一個character..so p + 1表示地址+ 1

p=(int *)p+1;因此* P = 0x03000000

是啊,that'all。感謝