首页 > 文章列表 > C中const char*p、char*const p和const char*const p之间的差异

C中const char*p、char*const p和const char*const p之间的差异

368 2023-09-02

指针

在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