[英]Why does char* cause undefined behaviour while char[] doesn't?
Attempting to modify a string literal causes undefined behavior: 尝试修改字符串文字会导致未定义的行为:
char * p = "wikipedia";
p[0] = 'W'; // undefined behaviour
One way to prevent this is defining it as an array instead of a pointer: 一种防止这种情况的方法是将其定义为数组而不是指针:
char p[] = "wikipedia";
p[0] = 'W'; // ok
Why does char*
cause undefined behaviour, while char[]
doesn't? 为什么
char*
会导致未定义的行为,而char[]
不会?
Any attempt to modify a C string literal has undefined behaviour . 任何修改C字符串文字的尝试都具有未定义的行为 。 A compiler may arrange for string literals to be stored in read-only memory (protected by the OS, not literally ROM unless you're on an embedded system).
编译器可能会安排将字符串文字存储在只读存储器中(受操作系统保护,而不是由ROM保护,除非您使用的是嵌入式系统)。 But the language doesn't require this;
但是语言不需要这个。 it's up to you as a programmer to get it right.
作为程序员,完全取决于您。
A sufficiently clever compiler could have warned you that you should have declared the pointer as: 一个足够聪明的编译器可能会警告您,您应该将指针声明为:
const char * p = "wikimedia";
though the declaration without the const
is legal in C (for the sake of not breaking old code). 尽管不带
const
的声明在C语言中是合法的(为了不破坏旧代码)。 But with or without a compiler warning, the const
is a very good idea. 但是无论有无编译器警告,
const
都是一个好主意。
(In C++, the rules are different; C++ string literals, unlike C string literals, really are const
.) (在C ++中,规则是不同的;与C字符串文字不同,C ++字符串文字实际上是
const
。)
When you initialize an array with a literal, the literal itself still exists in a potentially read-only region of your program image, but it is copied into the local array: 当您用文字初始化数组时,文字本身仍然存在于程序映像的潜在只读区域中,但会被复制到本地数组中:
char s[] = "wikimedia"; /* initializes the array with the bytes from the string */
char t[] = { 'w', 'i', ... 'a', 0 }; /* same thing */
Note that does not work -- arrays can only be initialized from a brace initializer, and char arrays additionally from a string literal. char u[] = *p
需要注意的是
不工作-阵列只能从一个支架初始化初始化,并且字符数组另外从一个字符串。 char u[] = *p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.