Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

c - const qualifier for pointers to pointers

I'm having a bit trouble deducing what is const, when applied to pointers to pointers, etc. i.e., what is const when you have

 const Foo **foo;

Can I here change something in **foo ? as in foo[0]->bar = 12;

What about:

 const Foo ***foo;
 Foo **const foo;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use cdecl to understand what a C declaration means.

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

thus you can change pointers, but not the value they're pointing to.

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

this, instead, is a cosnt pointer, pointing to a const pointer, to a non-const int: you cannot change pointed value, but it can be changed.


C uses the Clockwise/Spiral Rule, in a case where you have only modifiers at the left side of the variable (of foo) you read stuff going from right to left:

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

foo is a constant(1) pointer(2) to constant(3) pointer(4) to an integer(5).

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]

In this case foo is a constant(1) pointer(2) to constant(3) pointer(4) to a constant(5) integer(6) [or to an integer(5) which is constant(6)].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...