經典困惑:
char amessage[] = "now is the time"; // 數組:棧上分配,內容可改
char *pmessage = "now is the time"; // 指針:指向只讀數據段,不可改
amessage[1] = 'A'; // OK
pmessage[2] = 'B'; // 崩潰:Segmentation Fault / Access Violation
| 形式 | 存儲位置 | 可修改性 | 生命週期 |
|---|---|---|---|
char arr[] = "..." | 棧(或全局/靜態區) | ✅ 可讀寫 | 隨作用域 |
char *ptr = "..." | 只讀數據段(.rodata) | ❌ 僅讀 | 程序全周期 |
編譯器將字符串字面量放入只讀段,pmessage 只是持有其首地址。嘗試寫入觸發硬件保護異常。而 amessage[] 會在運行時將字面量拷貝到新分配的可寫內存。
char buf[100] = "init"; 或 malloc/new 動態分配。const char* 參數 → 用指針 const char *p = "literal";,編譯器會阻止誤寫。std::stringC++ 首選 std::string s = "text";,自動管理內存、可變長、支援 SSO(短字符串優化),完全避開此類坑。