通过声明为什么声明空隙F(const int的* P)被修改p
const int i;
显然i
不能被修改。
那么为什么声明
void f (const int *p)
正在修改p
? (我测试了它,它正在修改p
但不知道如何?)。
通过声明为什么声明空隙F(const int的* P)被修改p
const int i;
显然i
不能被修改。
那么为什么声明
void f (const int *p)
正在修改p
? (我测试了它,它正在修改p
但不知道如何?)。
的const
的位置。你倒着阅读:
const int *p
的意思是“p是一个指向int
这是不变的”int * const p
的意思是“p是一个常量指针到int
”const int * const p
的意思是“p是一个常数指针恒定int
“向后阅读对理解这一点非常有帮助。 – haccks
由于const
是int
通过p
,不p
指向 - 的指针int
。
const int *p
意味着p
是指向const int
,p
可以修改,*p
不。
用同样的方法
int *const p
意味着p
不能被修改,而*p
可以。
请注意,const int* p
与int const* p
相同。
简单的规则是声明从右到左读取:int const *p
意思是“p是指向常量int的指针”,int *const p
意思是“p是指向int的常量指针”。
在指针声明事项(实际的完整的规则比较复杂,可以用http://cdecl.org/为“解码” C风格的声明。)
+1为您的答案。 – haccks
因为在这个表达式中,p
是一个指向const int
。这意味着你可以改变什么p
指向。
这也意味着,“p”本身可以修改,但“p”的内容不能修改,所以*p = 10;
会产生错误。
一个例子清楚的事情:
#include <stdio.h>
void foo(const int *p)
{
int x = 10;
p = &x; //legally OK
// *p = 20; <- Results in an error, cannot assign to a read-only location.
printf("%d\n",*p);
}
int main(int argc, char *argv[])
{
const int x10 = 100;
foo(&x10);
return 0;
}
为了使上述程序不修改指针都:的
#include <stdio.h>
void foo(const int *const p)
{
int x = 10;
p = &x; //legally NOT OK, ERROR!
// *p = 20; <- Results in an error, cannot assign to a read-only location.
printf("%d\n",*p);
}
int main(int argc, char *argv[])
{
const int x10 = 100;
foo(&x10);
return 0;
}
感谢您举例说明。 – haccks
可能重复[是什么字符\ *常量和const的区别char \ *?](http://stackoverflow.com/questions/890535/what-is-the-difference-between-char-const-and-const-char) –
再次维基链接:[Const Correctness](http ://en.wikipedia.org/wiki/Const-correctness#Pointers_and_references) –
@GrijeshChauhan;句子**因此,'const'将名称修改为右边**在维基链接上引起混淆(第二段,第二行)。 – haccks