C++星号和括号运算符一起使用

Chl*_*ind 19 c++ operators

抱歉这个糟糕的标题,但我不知道如何更好地描述这个问题.

的意义是什么:

int (*x)[];
Run Code Online (Sandbox Code Playgroud)

以及如何初始化它?

我知道它不是int *x[]因为:

int a,b;
int (*x)[] = {&a, &b};
Run Code Online (Sandbox Code Playgroud)

不会编译.

先感谢您.

Jam*_*nze 26

类型声明具有类似表达式的语法,因此您可以像表达式一样解析它们:

      x       x is
     *x       a pointer
    (*x)[]    to an array of unknown dimensions
int (*x)[]    of int
Run Code Online (Sandbox Code Playgroud)

优先规则是,运营商向右结合除那些向左更紧,在每种情况下,操作者更靠近元件结合更紧,最后,该括号可用于改变这些绑定,所以:

int  *x[];    is an array of pointers,
int *(x[]);   as is this.
int (*x)[];   whereas here, the parentheses change the bindings.
Run Code Online (Sandbox Code Playgroud)


Att*_*ila 13

使用cdecl,您可以轻松确定类型:

将x声明为int数组的指针

所以你可以x用数组的地址初始化:

int a[]; // conceptual: error if compiled
x = &a;
Run Code Online (Sandbox Code Playgroud)

请注意,数组的大小是其类型的一部分,所以你不能大小的数组的地址分配N的指针大小的阵列M,其中,N!=M(这是上述错误的原因:你需要知道的大小声明它的数组)

int b[5];
int c[6];
int (*y)[6];
y = &b; // error
y = &c; // OK
Run Code Online (Sandbox Code Playgroud)