2013-07-15 37 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

相關問題