2013-07-15 63 views
1

通过声明为什么声明空隙F(const int的* P)被修改p

const int i; 

显然i不能被修改。
那么为什么声明

void f (const int *p) 

正在修改p? (我测试了它,它正在修改p但不知道如何?)。

+1

可能重复[是什么字符\ *常量和const的区别char \ *?](http://stackoverflow.com/questions/890535/what-is-the-difference-between-char-const-and-const-char) –

+0

再次维基链接:[Const Correctness](http ://en.wikipedia.org/wiki/Const-correctness#Pointers_and_references) –

+0

@GrijeshChauhan;句子**因此,'const'将名称修改为右边**在维基链接上引起混淆(第二段,第二行)。 – haccks

回答

7

const的位置。你倒着阅读:

  • const int *p的意思是“p是一个指向int这是不变的”
  • int * const p的意思是“p是一个常量指针到int
  • const int * const p的意思是“p是一个常数指针恒定int
+0

向后阅读对理解这一点非常有帮助。 – haccks

3

由于constint通过p,不p指向 - 的指针int

const int *p 

意味着p是指向const intp可以修改,*p不。

用同样的方法

int *const p 

意味着p不能被修改,而*p可以。

请注意,const int* pint const* p相同。

简单的规则是声明从右到左读取:int const *p意思是“p是指向常量int的指针”,int *const p意思是“p是指向int的常量指针”。

在指针声明事项(实际的完整的规则比较复杂,可以用http://cdecl.org/为“解码” C风格的声明。)

+0

+1为您的答案。 – haccks

3

因为在这个表达式中,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; 
} 
+0

感谢您举例说明。 – haccks

相关问题