有什么区别:
char * const
and
const char *
有什么区别:
char * const
and
const char *
当前回答
常量指针:在整个程序中,常量指针只能指向相应数据类型的单个变量。我们可以改变指针所指向的变量的值。初始化应该在声明本身的时候进行。
语法:
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修饰符应用于紧挨着它左边的项。唯一的例外是,当它的左边没有任何东西时,它就适用于它右边的东西。
这些都是“指向常量char的常量指针”的等效方式:
Const char * Const Const char Const * Char const * const Char const const *
Const char*是一个指向常量字符的指针 Char * const是一个指向字符的常量指针 Const char* Const是一个指向常量字符的常量指针
我记得捷克的一本关于C的书:读声明,你从变量开始向左走。 因此,对于
char * const a;
你可以读成:“a是指向char的常量指针类型的变量”,
char const * a;
你可以读成:“a是一个指向char类型常量变量的指针。我希望这能有所帮助。
奖金:
const char * const a;
您将读取为指向char类型的常量变量的is常量指针。
另一个经验法则是检查const的位置:
* =>之前存储的值为常量 * =>指针本身是常量
我猜你指的是const char *和char * const。
第一个const char *是一个指向常量字符的指针。指针本身是可变的。
第二个,char * const是一个指向字符的常量指针。指针不能改变,但它所指向的字符可以。
然后是const char * const,指针和字符不能改变。