我对 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/