[英]How do I have to read the following statement?
I liked to refresh my C++ skills and tried to programm a little Object, so I came about this expression: 我喜欢刷新我的C ++技能并试图编写一个小对象,所以我想到了这个表达式:
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.
我知道它是声明一个指向二维int数组的常量指针。
Thank you! 谢谢!
You should use the spiral rule to parse int (*const vectors)[2];
你应该使用螺旋规则来解析
int (*const vectors)[2];
: :
vectors
vectors
开始 const
means vectors
is constant, you cannot modify its value. const
表示vectors
是常量,您无法修改其值。 *
means pointer: vector
is a constant pointer *
表示指针: vector
是一个常量指针 [2]
means array of 2 . [2]
表示2的数组 。 vector
is a constant pointer to one or more arrays of 2 vector
是一个指向一个或多个2的数组的常量指针 int
gives the inner element type. int
给出内部元素类型。 vector
is a constant pointer to one or more arrays of 2 int
. vector
是一个指向一个或多个2 int
数组的常量指针。
Hence vector
can be made to point to an array of arrays of 2 int
. 因此,可以使
vector
指向2 int
的数组数组。 For example you can use vector
to manipulate a 2D matrix this way: 例如,您可以使用
vector
以这种方式操纵2D矩阵:
// 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
. 但请注意,必须初始化
vectors
,而不是分配vectors
,因为它被定义为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: 如果您希望
vectors
指向不应修改的2D矩阵,例如作为函数参数,则声明应为:
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. 最后,C和C ++中
const
的含义存在细微差别,但上面描述的解析方法适用于两种语言。
In a declaration, both prefix *
and postfix []
are operators that modify an identifier (or declarator). 在声明中,prefix
*
和postfix []
都是修改标识符(或声明符)的运算符。
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
. 问题是
[]
优先级高于*
,所以如果你把parens排除在外,你会将vectors
声明为int * const
的数组大小2。
The parens are needed to make vectors
a const pointer to int [2]
. 需要使用parens使
vectors
成为int [2]
的const指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.