gpt4 book ai didi

c++ - 访问字符指针

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

在C++中,为什么编译器不允许如下修改后面的字符指针

#include <iostream>

int main()
{
char* cp = "overflow";
cp[1]='p';
return 0;
}

输出:运行时崩溃。

但是字符数组允许,

#include <iostream>

int main()
{
char cps[] = "overflow";
cp[1]='p'; // this compiles fine and output is operflow
return 0;
}

只是想知道运行时发生了什么以及为什么会崩溃。谢谢。

最佳答案

字符串文字是 char const[] 类型的左值,其中 const 是重要的部分。尝试修改类型为 const 的对象是未定义的行为

根据 C++11 标准的第 2.14.5/8 段:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char, where n is the size of the string as defined below, and has static storage duration (3.7).

在第二种情况下(假设您的意思是 char cps[] = "overflow";,带方括号),您正在初始化一个非 const 字符串文字的拷贝。修改该拷贝即可。

另请注意,从字符串字面值到非-const char * 的转换在 C++03 中已弃用,在 非法 C++11。另一方面,这是合法的:

char const* cp = "overflow";
// ^^^^^

关于c++ - 访问字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924677/

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