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å²ã€‚
ç”案 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ä¸ä¼šæ”¹å˜ã€‚