除非它是sizeof
的操作或一元&
運算符,表達式的類型「T
」的N元素數組將被轉換爲「指向T
的指針」類型的表達式,並且該表達式的值將是該數組的第一個元素的地址。結果不是左值,這意味着它不能成爲任務的目標。
所以,給出的聲明
char mystr[20] = "hello there!";
下面都是真:
Expression Type Decays to Result
---------- ---- --------- ------
mystr char [20] char * address of mystr[0]
&mystr char (*)[20] n/a address of mystr
*mystr char n/a value of mystr[0], or 'h'
mystr[i] char n/a i'th character
&mystr[i] char * n/a address of mystr[i]
sizeof mystr size_t n/a 20 (number of bytes in array)
數組的地址是相同的數組的第一元素的地址(沒有存儲是預留一個mystr
變量與陣列元素本身分開的),所以表達式mystr
,&mystr
和&mystr[0]
都返回相同的值,但表達式的類型不同; mystr
和&mystr[0]
都具有類型char *
,但是&mystr
具有類型char (*)[20]
或「指向20元素陣列的char
」。
str2
的結果相同。
鑑於申報
char *p_mystr;
我們得到以下
Expression Type Result
---------- ---- ------
p_mystr char * value in p_mystr
*p_mystr char value of character pointed to by p_mystr
&p_mystr char ** address of p_mystr variable
sizeof p_mystr size_t number of bytes in pointer value
爲p_str2
表是一樣的。
現在這是一個匹配類型的問題。 p_mystr = mystr
可以工作,因爲這兩個表達式都有char *
; p_mystr
指向mystr[0]
。同樣,*p_mystr = mystr[2]
工程,因爲這兩個表達式都有類型char
。 val = *p_mystr++
相同,雖然在這種情況下注意*p_mystr++
被解析爲*(p_mystr++)
;該增量將應用於指針值,而不是字符值。
請注意,像p_mystr = &mystr;
這樣的表達式應該會爲您提供診斷,以確定類型不匹配。
您的問題標題提到const
指針和變量,雖然它不出現在問題主體中。基本上,任何類型的T
:
T *p0; // p0 is a non-const pointer to non-const T
const T *p1; // p1 is a non-const pointer to const T
T const *p2; // p2 is a non-const pointer to const T
T * const p3; // p3 is a const pointer to non-const T
const T * const p4; // p4 is a const pointer to const t
T const * const p5; // p5 is a const pointer to const t
能分解爲:
- 您可以寫信給
p0
(改變它指向別的東西)和*p0
(改變的事情被指向的);
- 您可以寫信給
p1
和p2
(改變它們指向別的東西),但你不能寫入*p1
或*p2
(不能改變的事情被指向的);
- 你不能寫
p3
(不能改變它指向別的東西),但你可以寫*p3
(改變指向的東西);
- 您不能寫信給
p4
或p5
(不能將它們更改爲指向其他內容),也不能寫入*p4
或*p5
(不能更改指向的內容)。
所以,如果你宣佈類似
const char *cptr = mystr;
你無法通過cptr
變量修改mystr
內容,即使mystr
未聲明const
本身。
注意,試圖走另外一條路,比如
const int foo = 5;
int *fptr = (int *) &foo;
*fptr = 6;
調用未定義的行爲;它可能會或可能不會工作,具體取決於實現(語言定義允許實現將const
限定的對象放在只讀存儲器中)。
1. 如果p_mystr
指向某處有效,也就是說。
您非常需要[this](http://www.c-faq.com/aryptr/index.html)! – haccks
也考慮http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c – Coconop
這裏沒有「指針常量」或「常量變量」,所以你的第一個問題是不清楚的。 – interjay