char *p="gooddad";
这样写,C里面是可以的。注意这里字符串字面量不一定是LS某几位一口咬定的const,尽管一些实现会放到常量区之类。
不过ISO C99 Annex. J 1里面明确指出
— The program attempts to modify a string literal (6.4.5).
是undefined behavior。
而C++里面字符串字面量是const的。
ISO C++ 2.13.4也明确指出:
The effect of attempting to modify a string literal is undefined.
此外,ISO C++ Annex. D指出:
D.4 Implicit conversion from const strings [depr.string]
1 The implicit conversion from const to non-const qualification for string literals (4.2) is deprecated.
仅仅是作为静态类型检查的特例;deprecated意味着这种char *p = "..."这类写法不过是为了兼容旧代码,遵循以后标准版本的编译器就算不给你编译过也没什么好奇怪的。现在的编译器一般会给出警告。
所以无论是C/C++,现写代码都应该用const char *p="gooddad";,而且不要去通过*(char*)p='k'之类的去修改p指向的内容。