C语言中 const char* p、char * const p 和 const char * const p 的区别
指针
在 C 编程语言中,*p 表示存储在指针中的值,而 p 表示该值的地址,被称为指针。
const char* 和 char const* 表示指针可以指向一个常量字符,并且该指针指向的字符的值不能更改。但是我们可以更改指针的值,因为它不是常量,并且可以指向另一个常量字符。
char* const 表示指针可以指向一个字符,并且该指针指向的字符的值可以更改。但是我们不能更改指针的值,因为它现在是常量,并且不能指向另一个字符。
const char* const 表示指针可以指向一个常量字符,并且该指针指向的 int 值不能更改。并且我们也不能更改指针的值,因为它现在是常量,并且不能指向另一个常量字符。
经验法则是从右到左命名语法。
// 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP