c - C中常量指针的奇怪行为

标签 c pointers constants

我对 C 中常量指针的奇怪行为有一些疑问。

1.

int x = 1;
const int *ptr = &x; 
x = 2;
printf("%d %d",*ptr, x);

由于指针 ptr 指向 const int,所以我预计第三行会出现错误。 (因为指针ptr中已经保存了“1”,加上“const”后指针中的值不能改变!)

2.

double rates[3] = {0.1,0.2,0.3};
const double *ptr = rates;
ptr[2] = 99.99;

从第二行开始,ptr是rates[0]的地址。我预计第三行不会出现错误,因为只有 *ptr = rates[0] 是 const double!

为什么会发生这样的事情?

最佳答案

记住

const double *ptr; // Remember it like (const double) <- *ptr;

表示 ptr 指向 const double,这只是意味着您不能使用指针本身 来更改指向的数据。但是,如果原始数据本身不是常量,您可以使用任何其他代理来修改值,就像您在

案例一

const int *ptr = &x; 
x = 2; // You use x itself to change the value

Since pointer ptr points to const int, I expected an error in the third line.

您不会收到错误,因为您没有通过指针更改 x。 如果你这样做了

*ptr=2; //you get an error

现在为 案例二

I expected no error to occurs from the third line

const double *ptr = rates;
ptr[2] = 99.99;

这与第一种情况相反,您使用指针来更改常量数据, 如果这条线是

rates[2] = 99.99;

你不会有任何错误。

关于c - C中常量指针的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38780948/

相关文章:

带函数的计算器

c - 使用 GNU/GCC 四精度库出错

c - 删除C中括号内的字符

C++ 从 Char 数组返回 T 类型的指针

c - 当任何两个数字之和超过最大值时,C 程序计算如何或以什么程序运行?

c - 在 C 中使用 ** 和不使用 ** 递增指针的区别

c - c中struct中struct的指针

c++ - 由于新的 const,C++11 对象在多线程环境中可能会变慢吗?

PHP - 如何检查输入过滤器是否有效?

c - 数组初始化时不兼容的指针类型