[問題] 字串利用strcpy問題~

看板C_and_CPP (C/C++)作者 (嘿嘿...)時間16年前 (2010/01/21 16:16), 編輯推噓2(2012)
留言14則, 2人參與, 最新討論串1/1
遇到的問題: (題意請描述清楚) 1.ptr="new"換成strcpy(ptr,"new")為何會錯? 從strcpy函數所要的參數列型態,我這樣放應該沒錯吧>"< 2.strcpy(str,"new")換成str="new"為何會錯? 我快被搞混了...哈... 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Dev-C++ 有問題的code: (請善用置底文標色功能) #include <iostream> #include <cstdlib> using namespace std; int main(void) { char *ptr="old"; cout << ptr << endl; cout << (void*)ptr <<endl; ptr="new"; //strcpy(ptr,"new"); cout << ptr << endl; cout << (void*)ptr <<endl; char str[]="old"; cout << str << endl; cout << (void*)str <<endl; strcpy(str,"new"); //str="new"; cout << str << endl; cout << (void*)str <<endl; system("pause"); return 0; } 補充說明: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.136.211.19

01/21 16:24, , 1F
char *ptr="old"; ptr指向的"old"為常數字串/字串常數.
01/21 16:24, 1F

01/21 16:25, , 2F
所以你不能對ptr的位址做寫入, ptr[0]='A';這樣都都行:)
01/21 16:25, 2F

01/21 16:26, , 3F
str="new"; 會錯是因為str是一個array, init成"old",
01/21 16:26, 3F

01/21 16:27, , 4F
你不能改變靜態陣列的啟始位址, 如int a, b[5]; b=&a;
01/21 16:27, 4F

01/21 16:28, , 5F
前面一個是指向常數的指標, 後面一個是init成某字串的陣
01/21 16:28, 5F

01/21 16:28, , 6F
列, 看起來用起來很像, 但是基本上還是有差的....@_@"
01/21 16:28, 6F

01/21 16:29, , 7F
2F: 這樣都"不"行. // 修正一下自己的typo....orz
01/21 16:29, 7F

01/21 16:33, , 8F
可是ptr="new"不就是對ptr指標寫入其所指的位址?
01/21 16:33, 8F

01/21 16:35, , 9F
會不會是我誤解strcpy的實作,而造成我一直不懂>"<
01/21 16:35, 9F

01/21 16:39, , 10F
所以pre="new"是ok的啊, 它會把"new"的位址寫給ptr啊.
01/21 16:39, 10F

01/21 16:40, , 11F
相對的, 原來ptr記碌的是"old"的位址, 這裡是不可寫的,
01/21 16:40, 11F

01/21 16:41, , 12F
strcpy會'copy'資料到ptr所在位址去, 即會嘗試把'n''e'
01/21 16:41, 12F

01/21 16:41, , 13F
'w''\0'寫入原來"old"的空間, 所以這裡是不合法的....
01/21 16:41, 13F

01/21 16:46, , 14F
謝謝V大,我懂了XD...
01/21 16:46, 14F
文章代碼(AID): #1BM0r5Lz (C_and_CPP)
文章代碼(AID): #1BM0r5Lz (C_and_CPP)