[課業] C++ 程式指標 疑問
題目出處:第4次全國各級農會-新進九職等以下-程式設計 (填充題 第3題)
https://i.imgur.com/qoZ2n9x.png

題目:
#include <iostream>
using namespace std;
int func(int x,int& y,int *z)
{
x=x+1;
y=y+2;
z=&x;
retuen x+y+*z; //我算出來的x=3,y=6,*z=3,與答案相同
}
int main()
{
int a=2,b=4,c=6;
printf("ANS1=%d",func(a,b,&c));
//我算出來的a=2,b=6,c=3,答案為a=2,b=6,c=6
printf("\ANS2=%d",a+b+c);
return 0;
}
答案(執行的輸出結果):
ANS1=12
ANS2=14
我算出來得答案為:
ANS1=12
ANS2=11
疑問點:
傳參考和傳址,不是都共用同一塊記憶體嗎?
為何 y=y+2; ,會更改到 b 的值,
而 z=&x; , c 的值還是維持在原本的 6 ?
https://i.imgur.com/c1i007A.png

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 192.83.186.60
※ 文章網址: https://www.ptt.cc/bbs/Examination/M.1525573003.A.7C7.html
※ 編輯: usisiu (192.83.186.60), 05/06/2018 10:17:05
推
05/06 10:49,
7年前
, 1F
05/06 10:49, 1F
→
05/06 10:49,
7年前
, 2F
05/06 10:49, 2F
推
05/06 10:52,
7年前
, 3F
05/06 10:52, 3F
→
05/06 10:52,
7年前
, 4F
05/06 10:52, 4F
感謝,原來 z 只是改指標
※ 編輯: usisiu (114.42.105.93), 05/06/2018 16:51:27
推
05/07 10:59,
7年前
, 5F
05/07 10:59, 5F
推
05/07 22:41,
7年前
, 6F
05/07 22:41, 6F
→
05/07 22:42,
7年前
, 7F
05/07 22:42, 7F
→
05/07 22:43,
7年前
, 8F
05/07 22:43, 8F
→
05/07 22:45,
7年前
, 9F
05/07 22:45, 9F
→
05/07 22:49,
7年前
, 10F
05/07 22:49, 10F
推
05/07 23:48,
7年前
, 11F
05/07 23:48, 11F