常量指针:cosnt pointer 所指向的地址上的数据是常量,所谓的常量指针,即const关键字,在*之前,如:const char *p。他的一般格式:const 数据类型 *变量名 ,也可以:数据类型 const *p;
指针常量:pointer const 所指向的地址是常量,所谓的指针常量,即*在关键字const之前,如:* const char p。他的一般格式:数据类型 * const 变量名
When we look at pointer declarations, reading from right-to-left gives a better idea about what the pointer actually points to.
Consider const int * p;
if we read right to left: p -> * -> int -> const. i.e. 'p is a pointer to an integer constant' rather than 'constant integer pointer' (if we read left to right) which doesn't give an idea if the pointer is constant or the value it is pointing to.
So reading it right to left gives clear idea that in the above declaration, p can be modified (like p++) but the value p is pointing to (*p) cannot be modified as it is pointing to a constant.
Let us consider another example int * const p;
. Again let us use the same right-to-left trick, p -> const ->* -> int. i.e. p is a constant pointer to an integer. In this case, p cannot be modified (like p++) but the value it is pointing to can be modified (like *p = 2).
Finally in const int * const p;
'p is a const pointer to an integer constant' by using the same RTL trick.
常量指针和指针常量的区分方法:
区分方法:我们从左到右,来区分指针常量和常量指针的区别
如:const char *p,我们从左往右都p>*>char>const,p是一个指向常量的指针而不是常量指针(从左往右读),所以p的地址能够改变,但是p指向的地址能够改变,即不能通过p来改变值,但是我们能够给p重新指向地址:
void main()
{
char *ch={"A"};
char const *p={"hello world"};
p=ch;
printf("%s\n",p);
}
如:char * const p ,我们从左到右p>const>*>char是一个常量指针,所以p不能被改变,但是我们能够通过p进行对刚才地址数据的更改
void main()
{
char str[6]={"hello"};
char * const p=str;
*p='A'
printf("%c\n",*p);
}
//输出A
但是
void main()
{
char *str={"hello"};
char * const p=str;
*p='A'
printf("%c\n",*p);
}//不会打印
错误:原因自己找去