有什么区别:
char * const
and
const char *
有什么区别:
char * const
and
const char *
当前回答
许多答案提供了具体的技术,经验法则等,以理解变量声明的特殊实例。但是有一个通用的技巧来理解任何声明:
顺时针/螺旋规则
A)
const char *a;
根据顺时针/螺旋规则,a是指向常量字符的指针。这意味着字符是不变的,但指针可以改变。即a = "其他字符串";没问题,但[2]= 'c';将无法编译
B)
char * const a;
根据规则,a是指向字符的const指针。例如,你可以做一个[2]= 'c';但是你不能用a = "other string";
其他回答
const * char是无效的C代码,没有意义。也许你想问const char *和char const *之间的区别,或者可能是const char *和char * const之间的区别?
参见:
什么是const指针(相对于指向const对象的指针)? C中的Const c++中const声明的区别 c++的const问题 为什么我可以改变一个const char*变量的值?
这里是一个详细的解释与代码
/*const char * p;
char * const p;
const char * const p;*/ // these are the three conditions,
// const char *p;const char * const p; pointer value cannot be changed
// char * const p; pointer address cannot be changed
// const char * const p; both cannot be changed.
#include<stdio.h>
/*int main()
{
const char * p; // value cannot be changed
char z;
//*p = 'c'; // this will not work
p = &z;
printf(" %c\n",*p);
return 0;
}*/
/*int main()
{
char * const p; // address cannot be changed
char z;
*p = 'c';
//p = &z; // this will not work
printf(" %c\n",*p);
return 0;
}*/
/*int main()
{
const char * const p; // both address and value cannot be changed
char z;
*p = 'c'; // this will not work
p = &z; // this will not work
printf(" %c\n",*p);
return 0;
}*/
const修饰符应用于紧挨着它左边的项。唯一的例外是,当它的左边没有任何东西时,它就适用于它右边的东西。
这些都是“指向常量char的常量指针”的等效方式:
Const char * Const Const char Const * Char const * const Char const const *
常量指针:在整个程序中,常量指针只能指向相应数据类型的单个变量。我们可以改变指针所指向的变量的值。初始化应该在声明本身的时候进行。
语法:
datatype *const var;
Char *const属于这种情况。
/*program to illustrate the behaviour of constant pointer */
#include<stdio.h>
int main(){
int a=10;
int *const ptr=&a;
*ptr=100;/* we can change the value of object but we cannot point it to another variable.suppose another variable int b=20; and ptr=&b; gives you error*/
printf("%d",*ptr);
return 0;
}
指向const值的指针:在这种情况下,指针可以指向任意数量的相应类型的变量,但不能改变指针在特定时间所指向的对象的值。
语法:
Const *var数据类型
Const char*属于这种情况。
/* program to illustrate the behavior of pointer to a constant*/
#include<stdio.h>
int main(){
int a=10,b=20;
int const *ptr=&a;
printf("%d\n",*ptr);
/* *ptr=100 is not possible i.e we cannot change the value of the object pointed by the pointer*/
ptr=&b;
printf("%d",*ptr);
/*we can point it to another object*/
return 0;
}
我想指出,使用int const *(或const int *)不是关于指向const int变量的指针,而是这个变量对于这个特定的指针是const的。
例如:
int var = 10;
int const * _p = &var;
上面的代码可以很好地编译。_p指向一个const变量,尽管var本身不是常量。