Reputation: 91
I liked to refresh my C++ skills and tried to programm a little Object, so I came about this expression:
int (*const vectors)[2];
How do I read it? I know that it is declaring a constant pointer pointing to a two dimensional int array.
Thank you!
Upvotes: 2
Views: 144
Reputation: 144520
You should use the spiral rule to parse int (*const vectors)[2];
:
vectors
const
means vectors
is constant, you cannot modify its value.*
means pointer: vector
is a constant pointer[2]
means array of 2. vector
is a constant pointer to one or more arrays of 2int
gives the inner element type.vector
is a constant pointer to one or more arrays of 2 int
.
Hence vector
can be made to point to an array of arrays of 2 int
. For example you can use vector
to manipulate a 2D matrix this way:
// allocate a 2D identity matrix:
int (*const vectors)[2] = malloc(sizeof(int[2][2]);
vectors[0][0] = vectors[1][1] = 1;
vectors[1][0] = vectors[0][1] = 0;
Note however that vectors
must be initialized, not assigned because it is defined as const
. If you intend for vectors
to point to a 2D matrix that should not be modified, for example as a function argument, the declaration should be:
void print_matrix(const int (*vectors)[2]);
Or
void print_matrix(int const (*vectors)[2]);
Finally, there are subtile differences for the meaning of const
in C and C++, but the parsing method describe above applies to both languages.
Upvotes: 4
Reputation: 3638
In a declaration, both prefix *
and postfix []
are operators that modify an identifier (or declarator).
The thing is that []
has higher precedence than *
, so if you left the parens out, you would declare vectors
as an array size 2 of int * const
.
The parens are needed to make vectors
a const pointer to int [2]
.
Upvotes: 0