confusing useage of pointers

本文详细解析了C语言中复杂的指针、数组及函数声明,并通过分解语法结构来帮助理解其含义。


In the following declarations, p is ...

int *p;pointer to int
int *p[10];array[10] of pointers to int
int (*p)[10];pointer to array[10] of int
int *p( ); function returning pointer to int
int (*p)( );pointer to function returning int
int *(*p)( );pointer to function returning pointer to int
int (*p[ ])( );array[ ] of pointers to function returning int
int (*(*p( ))[5])( );function returning pointer to array[5] of pointers to function returning int

The above become quite clear when we consider the precedence and associativity of operators:
   ( ) [ ]      {left to right}
   *            {right to left}

As an example what is p in the declaration:
int *((*(*p[5])( )))[10];

One nice and easy way to come to the correct conclusion is by assuming that you are the compiler and going through the following obvious steps. Obvious when you keep in mind the precedence and associativity of the operators at hand that is [], ( ), *.

First we have p[5] which is obviously an array, so we have array[5] of

Next is *p[5], which is a pointer, thus array[5] of pointers to

Then (*p[5])(), which represents a function, hence array[5] of pointers to function returning

Then *(*p[5])(), a pointer hence array[5] of pointers to function returning pointer to

Next consider ((*(*p[5])()))[10], which is an array, so we get array[5] of pointers to function returning pointer to array[10] of (an extra pair of ( ) above is of no use although it does no harm)

Then comes *((*(*p[5])()))[10], which is a pointer, so we get array[5] of pointers to function returning pointer to array[10] of pointers to

Lastly, the type which is int in this case which ultimately leads us to array[5] of pointers to function returning pointer to array[10] of pointers to int

When you are writing code all you have to do is to follow the reverse of the above steps, which is fairly easy.
Such a complicated (?? if you have gone through the above, it should seem too simple now) pointer/array/function/etc is seldom used, I think.And a nicer and more foolproof way to use such a thing is by using typedef.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值