gpt4 book ai didi

C++指针解释

转载 作者:太空狗 更新时间:2023-10-29 23:24:18 25 4
gpt4 key购买 nike

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”。谢谢!

最佳答案

编译器应该警告过你:

warning: deprecated conversion from string constant to 'char*''

您在这里所做的是将一些常量 char 数组分配给可变 char 指针,很像:

const char[] astring = "ababa";
char* mutablestring = astring; // shouldn't be possible
mutablestring[0] = 'o'; // change 'readonly' location

结果是,在运行时,一个指针指向您的二进制文件,并且您正在写入。但那是只读内存,所以……崩溃。

关于C++指针解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6096942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com