指针在C中分é…

时间:2013-07-05 20:40:28

标签: c pointers

int y=1;
int k=2; 
int *p1; 
int *p2; 
p1=&y;
p2=&k;
p1=p2;
*p1=3;
*p2=4;
printf("%d",y);

我的输出为1,有人å¯ä»¥è§£é‡Šä¸€ä¸‹ä¸ºä»€ä¹ˆ!!我原以为是4å²ã€‚

5 个答案:

答案 0 :(得分:4)

以下评论解释了这是如何è¿ä½œçš„:

int y=1;
int k=2; 
int *p1; 
int *p2; 
p1=&y; //pointer p1 holds the address of y
p2=&k; //pointer p2 holds the address of k
p1=p2; //pointer p1 now holds the address which p2 holds, which is the address of k
*p1=3; //the value which p1 points to is now 3 (so k equals 3 as well)
*p2=4; //the value which p2 points to is now 4 (so k equals 4 as well)
printf("%d",y); //y is still 1

但是,如果你printf("%d",k);,则会打å°å‡ºå€¼4

答案 1 :(得分:2)

为了ä¿æŒè¿™ä¸ªç®€å•ï¼Œæˆ‘们说&y=3å’Œ&k=4。

int y=1;
int k=2; 
int *p1; 
int *p2; 
p1=&y;  // p1=3
p2=&k;  // p2=4
p1=p2;  // p1=4
*p1=3;  // p1=4 so k becomes 3
*p2=4;  // p2=4 so k becomes 4
printf("%d",y); // we get 1 because y was never changed

答案 2 :(得分:1)

当你这样åšæ—¶ï¼š

p1=p2;

你基本上是将å˜é‡k的地å€ä»Žp2å¤åˆ¶åˆ°p1。所以在那一步之åŽï¼Œä¸¤ä¸ªæŒ‡é’ˆéƒ½æŒ‡å‘å˜é‡k,所以如果你å–消引用p1或p2,你实际上将改å˜å˜é‡k的值,而ä¸æ˜¯y。

当你这样åšæ—¶ï¼š

*p1 = 3;

您正在为å˜é‡k分é…3。然åŽå½“你这样åšï¼š

*p2 = 4;

您å†æ¬¡ä¸ºå˜é‡k分é…4。这就是为什么yä¿æŒä¸å˜çš„原因,当你打å°å®ƒæ—¶ä¼šç»™ä½ 1。

答案 3 :(得分:1)

声明p1=p2;å°†p1设置为指å‘å˜é‡k。所以以下两项任务都是:

*p1=3;  
*p2=4;

ä»…å½±å“å˜é‡k,因此yä»ä¸º1。

答案 4 :(得分:0)

当然,虽然我很想å¬å¬ä½ æ˜¯æ€Žä¹ˆåˆ°è¾¾çš„.4 p1被分é…了地å€ï¼ˆå³æŒ‡å‘)y,但åŽæ¥æœ‰2行被k的地å€å–代。因此,p1å’Œp2都ä¸æŒ‡å‘y,因此yä¸ä¼šæ”¹å˜ã€‚