[問題] char array, char* 的問題

看板C_and_CPP (C/C++)作者 (☆㊣↖煞氣ㄟ阿喂↘ξ★)時間15年前 (2010/11/26 01:37), 編輯推噓2(205)
留言7則, 3人參與, 最新討論串1/2 (看更多)
我想請問一下,我寫一個測試小程式如下,遇到一個很奇怪的問題我爬文沒找到: char str1[] = "This is a string"; int main() { //以下純粹為對照組 // int array[3] = {1, 2, 3}; int *k; k = array; cout<<k<<endl; //會show出&array[0] cout<<k+1<<endl; //會show出&array[1] cout<<k+2<<endl; //會show出&array[2] cout<<k[0]<<endl; //1 cout<<k[1]<<endl; //2 cout<<k[2]<<endl; //3 //以下為問題發生處 char *p = str1; char **pp; *pp = p; //會當機 pp = &p; //正常運作 cout<<p<<endl; //主要問題所在!! cout<<*pp<<endl; system("pause"); return 0; } pp和*pp各都是一個pointer沒問題,但是*pp指向p指向的位址(即str1)會當機呢? 此外,p好像被compiler當作string來看了, 因為cout<<p<<endl;不是像預期會出現&str1[0] 而是跑出This is a string 嗯....真是奇怪... 能不能請大家為我解惑一下? 先謝謝大家了! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.42.74.178 ※ 編輯: kkroy 來自: 114.42.74.178 (11/26 01:42) ※ 編輯: kkroy 來自: 114.42.74.178 (11/26 01:44)

11/26 01:45, , 1F
用 printf
11/26 01:45, 1F
※ 編輯: kkroy 來自: 114.42.74.178 (11/26 01:46) ※ 編輯: kkroy 來自: 114.42.74.178 (11/26 01:48)

11/26 01:54, , 2F
char **pp = new char*; *pp = p; 就可以了,可想想原因
11/26 01:54, 2F

11/26 01:54, , 3F
其實就是十三誡第三
11/26 01:54, 3F

11/26 01:54, , 4F
pp 沒有指向任何空間, 對它取值的動作會爆很合理
11/26 01:54, 4F

11/26 01:55, , 5F
至於如果 cout<<p<<endl; 想看到 &str1[0] 的話
11/26 01:55, 5F

11/26 01:56, , 6F
改成 cout << (void *)p << endl; 就可以了
11/26 01:56, 6F

11/26 01:56, , 7F
cout 對於 (char *) 的處理方式 就是當作字串來印
11/26 01:56, 7F
文章代碼(AID): #1CxfxM4d (C_and_CPP)
文章代碼(AID): #1CxfxM4d (C_and_CPP)