有什么区别:
char * const
and
const char *
有什么区别:
char * const
and
const char *
当前回答
const * char是无效的C代码,没有意义。也许你想问const char *和char const *之间的区别,或者可能是const char *和char * const之间的区别?
参见:
什么是const指针(相对于指向const对象的指针)? C中的Const c++中const声明的区别 c++的const问题 为什么我可以改变一个const char*变量的值?
其他回答
第一个是语法错误。也许你指的是两者的区别
const char * mychar
and
char * const mychar
在这种情况下,第一个指针是指向不能更改的数据的指针,第二个指针将始终指向相同的地址。
常量指针:在整个程序中,常量指针只能指向相应数据类型的单个变量。我们可以改变指针所指向的变量的值。初始化应该在声明本身的时候进行。
语法:
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;
}
为了避免混淆,总是附加const限定符。
int * mutable_pointer_to_mutable_int;
int const * mutable_pointer_to_constant_int;
int *const constant_pointer_to_mutable_int;
int const *const constant_pointer_to_constant_int;
两个规则
如果const在char和*之间,它将影响左边的那个。 如果const不在char和*之间,它将影响最近的一个。
e.g.
Char const *。这是一个指向常量char的指针。 Char * const。这是一个指向char类型的常量指针。
我猜你指的是const char *和char * const。
第一个const char *是一个指向常量字符的指针。指针本身是可变的。
第二个,char * const是一个指向字符的常量指针。指针不能改变,但它所指向的字符可以。
然后是const char * const,指针和字符不能改变。