這個問題幾乎在標題中。
編碼
void modify_str(char* str){
if(strlen(str) > 5) {
str[5] = 'x';
}
}
如果字串文字作為引數傳遞,將呼叫未定義的行為,即:
modify_str("some text");
或者
char *str = "some text";
modify_str(str);
有沒有辦法在運行時斷言作為引數傳遞的字串不是字串文字,而是可修改的字串?
uj5u.com熱心網友回復:
C 中的字串文字具有型別char [],因此沒有符合標準的方法來執行此操作。
但是,一些編譯器具有可以更改字串文字型別的標志,const char []以便您收到此類代碼的警告。
如果您使用 gcc,請添加-Wwrite-strings標志以使字串文字具有 type const char []。然后你會收到這樣的警告:
x1.c: In function ‘main’:
x1.c:14:16: warning: passing argument 1 of ‘modify_str’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
modify_str("some text");
^~~~~~~~~~~
x1.c:4:23: note: expected ‘char *’ but argument is of type ‘const char *’
void modify_str(char* str){
~~~~~~^~~
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470731.html
