为什么可以更改 const char* 变量的值?
为什么下面的 C 代码可以工作?
const char* str = NULL;
str = "test";
str = "test2";
既然 str 是一个指向常量字符的指针,为什么我们可以给它分配不同的字符串文字呢? 此外,我们如何保护str不被修改呢? 例如,如果我们后来将 str 分配给一个较长的字符串,而该字符串最终覆盖了内存的另一部分,那么这似乎可能是一个问题。
我应该补充一点,在我的测试中,我在每次赋值之前和之后打印出了 str 的内存地址,并且它从未改变。 所以,虽然str是一个指向const char的指针,但内存实际上是被修改的。 我想知道这是否是 C 的遗留问题?
Why does the following code in C work?
const char* str = NULL;
str = "test";
str = "test2";
Since str is a pointer to a constant character, why are we allowed to assign it different string literals? Further, how can we protect str from being modified? It seems like this could be a problem if, for example, we later assigned str to a longer string which ended up writing over another portion of memory.
I should add that in my test, I printed out the memory address of str before and after each of my assignments and it never changed. So, although str is a pointer to a const char, the memory is actually being modified. I wondered if perhaps this is a legacy issue with C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在更改指针,该指针不是 const (它指向的东西是 const)。
如果您希望指针本身为 const,则声明如下所示:
或
指向非常量数据的 Const 指针通常比指向 const 的指针不太有用。
You are changing the pointer, which is not const (the thing it's pointing to is const).
If you want the pointer itself to be const, the declaration would look like:
or
Const pointers to non-const data are usually a less useful construct than pointer-to-const.
阅读此内容的最简单方法是从变量名称开始并向左阅读:
注意:从右到左阅读在一般情况下不起作用,但对于简单的声明来说,这是一种简单的方法。 我发现了一个 java applet 基于“C 编程语言”中的代码“它可以破译声明并详细解释如何做到这一点。
The easiest way to read this is to start from the variable name and read to the left:
NOTE: the right-to-left reading does not work in the general case, but for simple declarations it's a simple way to do it. I found a java applet based on code from "The C Programming Language" that can decipher declarations with a full explanation of how to do it.
在相关说明中,一定要看看“const 指针与指向 const 的指针”。 它有助于实现某些人所说的常量正确性。 我把它保存在我的书签中,以便我时不时地参考它。
On a related note, definitely take a look at "const pointer versus pointer to const". It helps with what some people call const correctness. I keep it in my bookmarks so that I can refer to it every now and then.
您正在寻找的可能是语法...
请注意 char* 之后的“const”,它在尝试编译/构建时会产生编译器错误。
What you're looking for may be the syntax...
Notice the "const" after the char* which yields a compiler error when trying to compile/build.
此外,将变量声明为 const 意味着该变量是只读的; 这并不意味着该值是恒定的!
Besides, declaring a variable as const means that variable is read-only; it does not mean the value is constant!