当应用于指向指针的指针等时,我在推断什么是 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/