[問題] 定義字串與指標

看板C_and_CPP作者時間11年前 (2012/10/09 21:50), 編輯推噓0(006)
留言6則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) ubuntu 10.04 編譯器版本 g++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 無使用額外函數庫 問題(Question): 不了解錯誤訊息 餵入的資料(Input): g++ stringprac.cpp ./a.out 預期的正確結果(Expected Output): hello world 錯誤結果(Wrong Output): stringprac.cpp: In function ‘int main()’: stringprac.cpp:6: warning: deprecated conversion from string constant to ‘ char*’ stringprac.cpp:9: warning: deprecated conversion from string constant to ‘ char*’ 程式碼(Code):(請善用置底文網頁, 記得排版) 1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 char *str = "hello" ; 7 cout << str << endl; 8 9 str = "world"; 10 cout << str << endl; 11 12 return 0; 13 } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.254.147.177

10/09 21:51, , 1F
就是不能這樣用
10/09 21:51, 1F

10/09 21:53, , 2F
試試看把第6行改成 const char *str = "hello";
10/09 21:53, 2F

10/09 23:05, , 3F
感謝j大,成功了...想請問原因是為什麼...感謝!!
10/09 23:05, 3F

10/09 23:10, , 4F
string literal 會存在 rodata section,是 read-only
10/09 23:10, 4F

10/09 23:11, , 5F
不可修改,所以用 const
10/09 23:11, 5F

10/10 08:04, , 6F
都 #include <iostream>了,為何不用 string :)
10/10 08:04, 6F
文章代碼(AID): #1GT2kRF5 (C_and_CPP)