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

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

问题描述

为什么以下code用C的工作?

Why does the following code in C work?

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

由于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?

推荐答案

您正在改变的指针,这是不是常量(某事物的指向是常量)。

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:

char * const str = "something";

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

常量指向非const数据通常比指针到常量。不太有用的结构

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

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

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