C/C++中常量指针和指针常量浅析

    在C/C++中经常遇到const来修饰指针,这就出现了指针常量和常量指针。在使用中经常搞乱,对此进行一些梳理。

1.常量指针

       顾名思义,常量指针,本质是指针,只是用const常量修饰,表示这个指针是指向常量的(其实后面我们发现也可以指向变量)。这里指向向量的含义是,不能通过指针来修改变量的值。我们来看下面的例子:

int main(int argc, char *argv[])
{
	const int a = 10;
	int b = 20;
	const int* p_const;
	int *p_variable;
	p_const = &a; // const pointer can point to const or variable
	p_const = &b; // const pointer can point to const or variable
	//p_variable = &a;//[Error] error: invalid conversion from `const int*' to `int*'
	p_variable = &b;// Ok
	//*p_const =100;//[Error] error: assignment of read-only location
	*p_variable = 200;//OK, equal b =200
	b = 300;//b can be aassigned by variable b

	return 0;
}

       从上面结果可以得到结论:1.指针用const修饰,可以指向const类型的变量,也可以指向已经初始化的普通变量。2. 用const修饰的指针,不能通过指针来修改指向的变量值,但是可以通过变量定义的变量名来修改变量值(初始化后的普通变量)。3.用const修饰的指针,可以指向const修饰的变量,也可以指向不用const修饰的变量。但是,没有const修饰的指针只能修饰没有const修饰的变量,因此在C/C++中作为形式参数,const类型的指针经常会被用到。因为这样可以避免修改指向变量的值。

      简而言之:const修饰指针变量的目的就是防止用指针的方式来改变变量的值。

2. 指针常量

    指针常量指的是指针变量内存储的地址是常量,不能别修改。形式一般被写成:数据类型 * const Pointer。下面通过例子来说明:

int main(int argc, char *argv[])
{
	int a = 10;
	int b = 20;
	int * const const_pointer = &a; // value of const_pointer is a address
	int *pointer = &b;
	*const_pointer = 100;//ok equal a=100
	*pointer = 200; //ok equal b=200
	const_pointer = &b;//[Error] error: assignment of read-only variable `const_pointer'
	const_pointer ++;//[Error] error: assignment of read-only variable `const_pointer'
	pointer = &a;//OK, value of pointer is a address
	pointer ++;//OK, value of pointer increase by 1
		
	return 0;
}

       从上面的例子可以得出结论:1. 指针常量内存储的地址是不能改变的,因此该指针不能进行赋值等运算,但是指针指向的变量是可以改变的(常量指针常量就不可以了)。

      简而言之:指针常量和普通的变量常量类似,他存储的值(对于指针来讲是一个地址),一旦初始化后是不能改变的。

发布了10 篇原创文章 · 获赞 11 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u013323018/article/details/95947432