我们知道指针存储其操作数的地址值。
举例来说,如果char *ptr=a
,ptr
将存储变量a
的地址。 定义为常量的变量不能更改其值。 如果const int a=5
,那么像a++
之类的任何语句都是无效的,因为这会改变禁止的值。
类似地,如果指针ptr
指向变量a
且声明为const int *ptr=a
。像ptr=b
这样的语句将无效,因为ptr
不能指向b
,因为它是指向a
的常量指针。
了解了之后,碰巧有两个常量和指针的组合。
TYPE 1:指向恒定
const int a=5;
int* const ptr=a;
在这种情况下,该变量是一个恒定,其值不能被修改。 假设a的内存地址是0x9978
。因为,指针存储变量的地址,ptr=0x9978
。
分析以下语句: -
a=6; //Invalid: Value of a cannot be changed
*ptr=9; //Invalid: *ptr refers to a and will change its value.
int b=t;
ptr=b;//Valid: ptr is not constant and can point anywhere
希望这个概念现在很清楚。
TYPE 2:常数指针
在这里,指针是恒定的。一旦它指向一个变量,它就不能指向任何其他变量。它在其整个生命周期中存储一个不变的地址。
int a=7;
const int* ptr=a;
这里的值不能修改为ptr(0x9978)
的值。 再次看到语句: -
a=6; //Valid: Value of a can be changed
*ptr=9; //Valid: *ptr refers to a and its value can be altered.
int b=t;
ptr=b;//InValid: ptr is constant and cannot point anywhere else.
因此,ptr
不能指向任何其他变量现在。
回到你的问题,要更好地理解,请考虑char *
不作为指针,而是作为字符串类型(字符缓冲区)的变量!
char* barfoo = "variable_test"; //barfoo is a string storing 'variable_test'
const char* my_pointer_to_const_char = barfoo;
// This is type 2, constant pointer. Thus, my_pointer_to_const_char cannot
//point to any other variable and will always store the address of barfoo
barfoo = "changed!";
//this is perfectly valid as this statement will alter the value of string
//barfoo. my_pointer_to_const_char will still store the address of barfoo.
如果还有任何疑问,请随时发表评论:)
为什么不能'barfoo'改变?它是一个非const指针,指向非常量字符。你创建了一个指向其原始值的const指针并不相关。 –
,因为:“第一个值指向的值不能更改,但指针可以是” barfoo是指向的值。不是? –
这是一个不同的参考。 –