首页 > 解决方案 > C 类型符号

问题描述

我一直对 C 类型表示法的工作方式感到有些困惑。我无法访问 Google,并且 Bing 正在显示垃圾结果。

例如:什么int *(*)[]意思?我已经知道它是一个指向整数指针数组的指针(我认为),但是为什么呢?特别是,我对括号在做什么感到困惑。是的,int **[]将是一个指向指针的数组,但为什么会()改变呢?

标签: ctypes

解决方案


要读取此类类型,请在心里为表达式添加一个变量名,以将其转换为有效的声明。然后从内到外阅读它,就像阅读 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

如您所见,括号具有选择.*之前的第一个运算符的效果[]。后者具有更高的优先级,因此如果需要指向数组的指针,则需要引入括号。


有三个与类型声明相关的运算符,了解它们的优先级很重要:

High precedence:
[]    array subscript declares an array
()    function call declares a function

Low precedence:
*     dereference operator declares a pointer

因为 的*优先级低于()or [],所以您需要添加额外的括号来声明指向数组或函数的指针:

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 中的类型表达式就不会再让你感到困惑了。


推荐阅读