的char * p =" orkut的" VS为const char * p =" orkut的" [英] char *p="orkut" vs const char *p="orkut"
问题描述
char *p="orkut" vs const char *p="orkut"
什么btwn这两个的区别...
whats the difference btwn these two...
修改
从Bjarne的Stroustrup的,第3版第90页
from bjarne stroustrup,3rd edition page 90
void f()
{
char* p="plato";
p[4]='e' // error: assign to const;result is undefined
}
的这种错误cannont是一般的b抓住,直到运行时间和实现他们的这一规则的实施有所不同的
与为const char * p =同柏拉图
Same with const char *p="plato"
这就是为什么IAM要求探源......请告诉我的常量的意义在这里..
Thats why iam asking the diffrence... Whats the significance of const here..
推荐答案
的为const char *
变种是正确的。
您不应该改变来自一个字符串字面量的内存(称为静态存储通常情况下)。它是只读存储器。
You should not change memory that comes from a string literal (referred to as static storage usually). It is read only memory.
不同的是,在的char *
变种将让你写的语法来更改它通过取消引用它指向的数据。但什么它实际上是不确定的。
The difference is that the char*
variant will allow you to write the syntax to change the data that it points to by dereferencing it. What it actually does though is undefined.
//Option 1:
char *p = "orkut";
*p = 'x';//undefined behavior
//Option 2:
const char *q = "orkut";
*q = 'x';//compiling error
我宁愿有选择2发生在我身上。
I would rather have option 2 happen to me.
这篇关于的char * p =" orkut的" VS为const char * p =" orkut的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!