为什么我可以更改 const char* 变量的值? [英] Why can I change the value of a const char* variable?

查看:17
本文介绍了为什么我可以更改 const char* 变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的 C 代码可以工作?

Why does the following code in C work?

const char* str = NULL;
str = "test";
str = "test2";

既然 str 是一个指向常量字符的指针,为什么我们可以给它分配不同的字符串字面量呢?此外,我们如何保护 str 不被修改?例如,如果我们稍后将 str 分配给一个更长的字符串,该字符串最终会覆盖另一部分内存,这似乎是一个问题.

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.

我应该在我的测试中补充一点,我在每次分配之前和之后打印出 str 的内存地址,它从未改变过.因此,尽管 str 是一个指向 const char 的指针,但实际上内存正在被修改.我想知道这是否是 C 的遗留问题?

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?

推荐答案

你正在改变指针,它不是 const(它指向的东西是 const).

You are changing the pointer, which is not const (the thing it's pointing to is const).

如果您希望指针本身为 const,则声明如下:

If you want the pointer itself to be const, the declaration would look like:

char * const str = "something";

char const * const str = "something";  // a const pointer to const char
const char * const str = "something";  //    same thing

指向非 const 数据的 const 指针通常不如指向 const 的指针有用.

Const pointers to non-const data are usually a less useful construct than pointer-to-const.

这篇关于为什么我可以更改 const char* 变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆