我一直对 C 类型表示法的工作原理感到有点困惑。我无法访问 Google,Bing 显示的是垃圾结果。
例如:int *(*)[]
是什么意思?我已经知道它是一个指向整数指针数组的指针(我认为),但为什么呢?特别是,我对括号的作用感到困惑;是的,int **[]
将是指向指针的指针数组,但为什么 ()
会改变它?
最佳答案
要读取此类类型,请在心里为表达式添加一个变量名,以将其变成有效的声明。然后从里到外读它,就像你在 C 中读所有的变量声明一样:
int **[] -> int **a[];
a[] //[] has higher precedence than *, so `a` is an array
*a[] //this array contains pointers
**a[] //which dereference to pointers
int **a[]; //which dereference to int
因此,int**[]
是指向 int
的指针的指针数组的类型。
对于另一种类型,我们得到:
int *(*)[] -> int *(*a)[];
*a //a is a pointer
(*a) //(precedence control, only)
(*a)[] //which dereferences to an array
*(*a)[] //which contains pointers
int *(*a)[]; //which dereference to int
因此,int*(*)[]
是指向 int
的指针的数组指针类型。
如您所见,括号的作用是选择 []
之前的第一个 *
运算符。后者的优先级更高,所以如果需要指向数组的指针,需要引入括号。
与类型声明相关的运算符有 3 个,了解它们的优先级很重要:
High precedence:
[] array subscript declares an array
() function call declares a function
Low precedence:
* dereference operator declares a pointer
因为 *
的优先级低于 ()
或 []
,所以您需要添加额外的括号来声明指向数组的指针或函数:
int *a[]; //array of pointers, as a cast: `(int*[])`
int (*a)[]; //pointer to an array, as a cast: `(int(*)[])`
int *a(); //function returning a pointer, as a cast: `(int*())`
int (*a)(); //pointer to a function returning an `int`, as a cast: `(int(*)())`
一旦理解了这个原则,C 中的任何类型表达式都不会再让您感到困惑。
关于C 类型表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62652500/