C++指针解释
char* pstr[] = { "Robert Redford", // Initializing a pointer array
"Hopalong Cassidy",
"Lassie",
"Slim Pickens",
"Boris Karloff",
"Oliver Hardy"
};
如果我像下面这样写:
*pstr[0] = 'X';
程序可以编译,但执行此语句时崩溃。为什么?我认为 *pstr[0] 是“R”,这样我就可以从“R”更改为“X”。 谢谢!
char* pstr[] = { "Robert Redford", // Initializing a pointer array
"Hopalong Cassidy",
"Lassie",
"Slim Pickens",
"Boris Karloff",
"Oliver Hardy"
};
If I write like below:
*pstr[0] = 'X';
The program can compile but crashes when this statement is executed. Why? I thought *pstr[0] is 'R' so that I can change from 'R' to 'X'.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编译器应该警告您:
您在这里所做的是将一些常量 char 数组分配给可变 char 指针,很像:
结果是,在运行时,一个指向您的二进制文件的指针,并且您正在编写到。但那是只读内存,所以......崩溃。
The compiler should have warned you:
What you're doing here is assigning some constant char arrays to a mutable char pointer, much like:
The result is, at run time, a pointer that points into your binary, and that you're writing to. But that's readonly memory, so.. crash.
您正在创建一个指向
const char*
数组的指针。所以 pstr[0] 指向一个 const char* 并且你不能改变它的值。以这种方式编写此代码是一个很好的编程习惯,因此如果您尝试更改该值而不是运行时错误,您将收到编译器错误:
You are making a pointer to an array of
const char*
s. So pstr[0] is pointing to aconst char*
and you can't change it's value.It's a good programming practice to write this code in this way so you'll get a compiler error if you try to change the value instead of runtime error:
字符串文字是常量,因此您无法更改它们。
允许从
const char*
到char*
的转换,只是为了允许 C 获得const
之前的旧 C 代码。The string literals are constants, so you cannot change them.
Conversion from
const char*
tochar*
is allowed just to allow old C code from the time before C gotconst
.pstr
是一个包含const *char
元素的数组。修改只读存储器的结果是未定义的。如果您知道每个字符串的最大大小,您可以像这样声明pstr
pstr
is an array withconst *char
elements. The result of modifying read-only memory is undefined. If you know the max size of each string you can declarepstr
like so