Difference of various const declarations in C
Possible Duplicate:
What is the difference between const int*, const int * const, and int const *?
以下两者有什么区别?
1 2 3 | char const *p; const char *p; char *const p; |
还有一个好地方,我可以重新学习C和C++?我好像忘了,面试让我很难过…
第一个是相同的。
的伎俩是,读它向后。
因此,第一个是:
1 2 3 4 | backwards: p * const char read: p is a pointer to a const char meaning: you can change p to point a at something else, but you can't change what it points at |
和最后一个:
1 2 3 4 | backwards: p const * char read: p is a const pointer to a char meaning: p is a pointer which you can't change what it points at, but you can change the thing it points to. |
1 | p += 1; |
但不是这样的
1 | *p += 1; |
1 | *p += 1; |
但不是这样的
1 | p += 1; |
我很喜欢cplusplus.com研究参考和学习。
第一个是相同的均值和指向字符的指针。第二是一个常数(非const pointer to)字符。在第一个案例,你可以/能改变困境的指针,但在什么点。在第二个案例中,你可以更改在什么点,但不是很不同的内存指针的问题。
主要的事情是保持指针声明/轨道的定义是:"*"。
1 | char X * Y ptr; |
无论是"X"或"Y"
有两个单独的事情在这里,a的指针和数据信息点,和
没有
1 2 3 | char *p ="hello"; ++p; // Changes the pointer, now points to 'e' *p = 'u'; // Changes the data, now"hullo" |
一个例子
他说:"TC读宣言,向后。
你可以改变它的指针,但不是数据点
1 2 3 4 5 | // These two declarations have the same effect char const *p ="hello"; // Pointer to constant char const char *p ="hello"; // Pointer to char which is constant ++p; // OK *p = 'u'; // Won't compile |
2你可以改变"你好",但没有指针
1 2 3 | char * const p ="hello"; // Constant pointer to char ++p; // Won't compile *p = 'u'; // OK |
是不可变的,你可以让
1 2 3 | char const * const p ="hello"; // Constant pointer to constant char ++p; // Wont' compile *p = 'u'; // Wont' compile |
作为附加的奖励,读取STL STL的有效使用时间。
本代码illustrates它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | int main() { char a = 'a'; char b = 'b'; char const *p1; //p1 is the same as p2 const char = char const const char *p2; char *const p3 = &a; //Can only assign like this. p1 = &a; p2 = &a; *p1 = b; //Will not compile - cannot change the value via the pointer. *p2 = b; //Will not compile - cannot change the value via the pointer. p3 = &a; //Will not compile - cannot reassign the pointer printf("p1 = %c ",*p1); printf("p2 = %c ",*p2); printf("p3 = %c ",*p3); return 0; } |