对于 const int *ptr
你不能改变ptr指向的值
int main()
{
const int *p;
int a=5;
p=&a;
printf("%d",++(*p));
}
上面的程序抛出错误。这很公平。
但是为什么下面的代码不会抛出错误。
int main()
{
const int const *p;
int a=5;
p=&a;
a=100; // changing the content pointed by the constant pointer
printf("%d",(*p));
}
我正在更改 const 指针指向的值。即我正在更改 var a 的值 5 到 100?
最佳答案
语句 a = 100;意味着您正在使用变量 a 将值更改为 100,该变量不是常量。因此您将能够更改 a 的值。
但是如果您尝试运行以下代码:
int main()
{
const int const *p;
int a=5;
p=&a;
*p=100;
// a=100;
printf("(*p)=%d",(*p));
return 0;
}
这会给您带来错误,因为您要更改值的指针指向只读位置。因为您已将指针位置的值声明为常量。
这里 a 和 p 是两个不同的变量,它们有自己的属性。
关于C中常量指针的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20580070/