C 语言中 const int*、const int * const 和 int const * 之间的区别
cserver side programmingprogramming更新于 2024/11/16 18:00:00
指针
在 C 编程语言中,*p 表示存储在指针中的值,p 表示值的地址,称为指针。
const int* 和 int const* 表示指针可以指向一个常量 int,并且该指针指向的 int 的值不能更改。但我们可以更改指针的值,因为它不是常量,它可以指向另一个常量 int。
const int* const 表示指针可以指向一个常量 int,并且该指针指向的 int 的值不能更改。而且我们也不能改变指针的值,因为它现在是常量,不能指向另一个常量 int。
经验法则是从右到左命名语法。
// 指向常量 int 的常量指针 const int * const // 指向常量 int 的指针 const int *
示例 (C)
取消注释注释的错误代码并查看错误。
#include <stdio.h> int main() { //Example: int const* //Note: int const* is same as const int* const int p = 5; // q is a pointer to const int int const* q = &p; //Invalid asssignment // value of p cannot be changed // error: assignment of read-only location '*q' //*q = 7; const int r = 7; //q can point to another const int q = &r; printf("%d", *q); //Example: int const* const int const* const s = &p; // Invalid asssignment // value of s cannot be changed // error: assignment of read-only location '*s' // *s = 7; // Invalid asssignment // s cannot be changed // error: assignment of read-only variable 's' // s = &r; return 0; }
输出
7