有什么区别:
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";
其他回答
常量指针:在整个程序中,常量指针只能指向相应数据类型的单个变量。我们可以改变指针所指向的变量的值。初始化应该在声明本身的时候进行。
语法:
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;
}
这里x基本上是一个字符指针,指向一个常数值 Char * const x是一个字符指针,它是一个常量,但是它指向的位置可以改变。 Const char* Const x是1和2的组合,意味着它是一个指向常量值的常量字符指针。 Const *char x将导致编译器错误。它不能被宣布。 Char const * x等于点1。
经验法则是,如果const是var名称,那么指针将是常量,但指向的位置可以改变,否则指针将指向一个常量位置,指针可以指向另一个位置,但指向的位置内容不能改变。
我猜你指的是const char *和char * const。
第一个const char *是一个指向常量字符的指针。指针本身是可变的。
第二个,char * const是一个指向字符的常量指针。指针不能改变,但它所指向的字符可以。
然后是const char * const,指针和字符不能改变。
经验法则:从右向左阅读定义!
Const int *foo;
意思是“foo指向(*)一个不能改变的int (const)”。 对于程序员来说,这意味着“我不会改变foo所指向的值”。
*foo = 123;或者foo[0] = 123;是无效的。 Foo = &bar;是被允许的。
Int *const foo;
意思是“foo不能改变(const)并将(*)指向int”。 对于程序员来说,这意味着“我不会改变foo引用的内存地址”。
*foo = 123;或者foo[0] = 123;是被允许的。 Foo = &bar;是无效的。
Const int * Const foo;
意思是“foo不能改变(const)并将(*)指向一个不能改变的int (const)”。 对于程序员来说,这意味着“我不会改变foo所指向的值,也不会改变foo所指向的地址”。
*foo = 123;或者foo[0] = 123;是无效的。 Foo = &bar;是无效的。
另一个经验法则是检查const的位置:
* =>之前存储的值为常量 * =>指针本身是常量