指针在c编程语言中,*p表示指针中存储的值,p表示值的地址,被称为指针。
const char*和char const*表示指针可以指向一个常量字符,指针指向的字符的值不能被改变。但是我们可以改变指针的值,因为它不是常量,可以指向另一个常量字符。
char* const表示指针可以指向一个字符,指针指向的字符的值可以被改变。但是我们不能改变指针的值,因为它现在是常量,不能指向另一个字符。
const char* const表示指针可以指向一个常量字符,指针指向的字符的值不能被改变。我们也不能改变指针的值,因为它现在是常量,不能指向另一个常量字符。
命名语法的原则是从右到左。
// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *
示例(c)取消注释错误的代码并查看错误。
实时演示
#include <stdio.h>
int main() {
//example: char const*
//note: char const* is same as const char*
const char p = 'a';
// q is a pointer to const char
char const* q = &p;
//invalid asssignment
// value of p cannot be changed
// error: assignment of read-only location '*q'
//*q = 'b';
const char r = 'c';
//q can point to another const char
q = &r;
printf("%c
", *q);
//example: char* const
char u = 'd';
char * const t = &u;
//you can change the value
*t = 'e';
printf("%c", *t);
// invalid asssignment
// t cannot be changed
// error: assignment of read-only variable 't'
//t = &r;
//example: char const* const
char const* const s = &p;
// invalid asssignment
// value of s cannot be changed
// error: assignment of read-only location '*s'
// *s = 'd';
// invalid asssignment
// s cannot be changed
// error: assignment of read-only variable 's'
// s = &r;
return 0;
}
输出c
e
以上就是c中const char*p、char*const p和const char*const p之间的差异的详细内容。