如何破译C中的复杂指针声明?

Kor*_*gay 7 c pointers declaration

所以我想举个例子:

int *pi; // pi is a pointer that points to an integer
const int *cpi; // cpi is a pointer that points to a constant integer
char *pc; // pc is a pointer to a char 
Run Code Online (Sandbox Code Playgroud)

我怎么读这些:

char **x; //x is a pointer to a char pointer?
char *y[];
char **z[];
Run Code Online (Sandbox Code Playgroud)

谢谢.

hac*_*cks 11

cdecl.org经常与这些问题联系在一起.毫无疑问,它更容易破译任何复杂的声明,但同时它只是提供一个抽象的信息.作为C或C++程序员,人们应该知道如何手动解密复杂的声明.螺旋规则在某种程度上有所帮助,但在某些情况下失败.这个答案将帮助程序员手动解密任何复杂的声明.


记住这两个简单的规则:

  1. 始终从内到外阅读声明.
  2. 当有选择时,总是喜欢[]()结束*.

第一条规则简单地说明,找到正在声明的变量并开始从中解密声明.

对于第二个规则,如果*在标识符之前和/ []()之后,则标识符表示数组或函数(分别),而不是指针.

例1:

char *y[5]; 
Run Code Online (Sandbox Code Playgroud)
  • 变量/标识符是y.
  • *先于y和随后[].
  • y 必须是一个数组.

结合上面的解密将导致:y是一个5指针数组char.

另请注意,您始终可以使用括号覆盖[]或的正常优先级().

例2:

void (*pf) (int);
Run Code Online (Sandbox Code Playgroud)
  • 变量/标识符是pf.
  • *pf 括在括号中,它必须是一个指针.
  • ()如下*pf,意味着pf必须指向一个功能.
  • 由于()封闭int,函数必须要求一个类型的参数int.

所以,pf是一个指向函数的指针,它需要一个int参数并且什么也不返回.

现在,在解读以下声明后你会得到什么?

int *(*a[5])(void);  
Run Code Online (Sandbox Code Playgroud)

回答:

a是一个指向函数的指针数组,它不需要参数并返回指针int.


注意: 请注意两者

char *y[];
char **z[];  
Run Code Online (Sandbox Code Playgroud)

如果未将它们声明为函数的参数,则会导致编译错误.如果它们是函数的参数,则char *y[]相当于char **ychar **z[]等同于char ***z.
如果不是这样,那么你需要像我在第一个例子中那样指定维度.


mcl*_*fix 5

一些示例 C 声明取自 HELPPC 实用程序(由 David Jurgens),它在九十年代拯救了我的(编程)生活(该实用程序的在线版本在这里: http: //stanislavs.org/helppc

int i;                  i as an int
int *i;                 i as a pointer to an int
int **i;                i is a pointer to a pointer to an int
int *(*i)();            i is a pointer to a function returning a
                          pointer to int
int *(*i[])();          i is an array of pointers to functions
                          returning pointers to an int
int *i[5];              i is an array of 5 pointers to int
int (*i)[5];            i is a pointer to an array of 5 ints
int *i();               i is a function returning a pointer to an int
int (*i)();             i is a pointer to a function returning int
int *(*(*i)())[5]       i is a pointer to a function returning a
                          pointer to an array of 5 pointers to an int
Run Code Online (Sandbox Code Playgroud)