指向指针的指针的 const 限定符

标签 c

当应用于指向指针的指针等时,我在推断什么是 const 时遇到了一些麻烦。 即,什么是 const 当你有

 const Foo **foo;

我可以在这里更改 **foo 中的内容吗?如 foo[0]->bar = 12;

关于:

 const Foo ***foo;
 Foo **const foo;

最佳答案

你可以使用 cdecl了解 C 声明的含义。

const int **foo;
declare foo as pointer to pointer to const int

因此您可以更改指针,但不能更改它们指向的值。

int * const * const foo;
declare foo as const pointer to const pointer to int

相反,这是一个 cosnt 指针,指向一个 const 指针,指向一个非常量 int:您不能更改指向的值,但它可以更改。


C 使用 Clockwise/Spiral Rule ,在变量(foo)的左侧只有修饰符的情况下,您会从右到左阅读内容:

int(5) *(4) const(3) *(2) const(1) foo;

foo 是指向常量(3) 的常量(1) 指针(2) 指向整数(5) 的指针(4)。

int(6) const(5) *(4) const(3) *(2) const(1) foo;
const(6) int(5) *(4) const(3) *(2) const(1) foo; // [same as above]

在这种情况下,foo 是常量(1) 指针(2) 到常量(3) 的指针(4) 到常量(5) 整数(6) [或整数(5 ) 是常量 (6)]。

关于指向指针的指针的 const 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246445/

相关文章:

对包含前缀和后缀运算符的 printf() 感到困惑

c - 根据条件从字符串中提取子字符串

c++ - 比较指针对象是否相等

c - qsort 指向链表的指针数组,按结构成员值

无法在没有 toupper 的情况下使用 C 中的循环将 char* 指针转换为小写/大写

连接服务器-客户端

c - makefile 找不到 .o 文件

c - C 中的二叉搜索树并为重复键构建链表

c - 值0的套接字类型是什么类型?

c - mvaddch 不会覆盖屏幕上的字符