gpt4 book ai didi

char *p ="orkut"与 const char *p ="orkut"

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:40 24 4
gpt4 key购买 nike

 char *p="orkut" vs const char *p="orkut"

这两个有什么区别...

编辑

来自 bjarne stroustrup,第 3 版第 90 页

void f()
{

char* p="plato";
p[4]='e' // error: assign to const;result is undefined

}

这种错误一般无法在运行时被捕获,并且实现在执行此规则方面有所不同

与 const char *p="plato"相同

这就是为什么我要问差异...这里 const 的意义是什么...

最佳答案

const char* 变体是正确的。

您不应该更改来自字符串文字的内存(通常称为静态存储)。它是只读存储器。

不同之处在于 char* 变体将允许您编写语法以通过取消引用来更改它指向的数据。它实际做什么虽然是未定义的。

//Option 1:
char *p = "orkut";
*p = 'x';//undefined behavior


//Option 2:
const char *q = "orkut";
*q = 'x';//compiling error

我宁愿选项 2 发生在我身上。

关于char *p ="orkut"与 const char *p ="orkut",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2563099/

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