請問這句code有錯? (char*和string的問題)

2011-05-23 8:12 pm
紅色那句code在visual C++ RUN有run time error, 請問那句code是在所有C++ compiler都有問題,還是只有某一些C++ compiler 才有問題?

class book{
public :
char *bname;
book(char* bname){
this->bname=bname;
}
};
int main(){
book book01("ABC");
book01.bname[0]='Z';
}

回答 (2)

2011-05-24 5:35 am
✔ 最佳答案
所有string constant是存放在受保護而不能改動的記憶體位置,你硬把string constant cast成char*再改動其內容當然會有run-time error。這是錯誤的code,所有compiler都會compile出有問題的執行檔(除非你在一個沒有保護好記憶體的OS上運行)。實際上我很好奇VC++竟然沒有給予警告。如果你想assign "ABC"到char* bname,應該使用strcpy():#include <cstring>

class book {
public :
char *bname;

book(const char* bname) {
const size_t sz = strlen( bname ) +1;
this->bname = new char[sz];
fill( this->bname, this->bname +sz, '\0' );
strcpy( this->bname, bname );
}
};
你只要謹記string constant是constant,是const char*而非char*,就不會出錯的了。

2011-05-24 04:14:35 補充:
我想改一下我的字眼。
那句code本身其實是沒錯的,也因此沒有compiler會給你error(GCC會給warning),只是他所執行的動作不被Windows(和其他所有modern OS)所許可(安全理由)而被強制中止執行,所以出現run-time error。

2011-05-24 04:22:30 補充:
也就說,如果你找到一個不對特定記憶位置進行唯讀保護的OS,你的程式將會好好的運行,而"ABC"這string constant往後就會變成"ZBC"。
2011-05-23 10:58 pm
5 係所有都會出問題
有 d compile 出黎 ge exe 係可以 run 到
視乎佢點處理你個 constant "abc"
不過其實你個種做法都 5 安全
真係有必要咁樣做嗎?


收錄日期: 2021-04-13 17:59:55
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20110523000051KK00260

檢視 Wayback Machine 備份