如何检查作为参数传递的字符串是否是可修改的字符串

How to check if a string passed as argument is a modifiable string

标题中的问题差不多

代码

void modify_str(char* str){
    
    if(strlen(str) > 5) {
       str[5] = 'x';
    }
}

如果将字符串文字作为参数传递,将调用未定义的行为,:

modify_str("some text");

char *str = "some text";
modify_str(str);

有没有办法在运行时断言作为参数传递的字符串不是字符串文字,而是可修改的字符串?

C 中的字符串文字具有 char [] 类型,因此没有 standard-compliant 方法可以做到这一点。

然而,有些编译器有标志,可以将字符串文字的类型更改为 const char [],这样您就会收到这样的代码的警告。

如果您使用的是 gcc,请添加 -Wwrite-strings 标志以使字符串文字具有类型 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){
                 ~~~~~~^~~