Equivalent C declarations

有些话、适合烂在心里 提交于 2019-12-03 03:48:33

They are not equal. in the first case x is a pointer to an array of 10 integers, in the second case x is an array of 10 integers.

The two types are different. You can see they're not the same thing by checking sizeof in the two cases.

Follow this simple process when reading declarations:

Start at the variable name (or innermost construct if no identifier is present. Look right without jumping over a right parenthesis; say what you see. Look left again without jumping over a parenthesis; say what you see. Jump out a level of parentheses if any. Look right; say what you see. Look left; say what you see. Continue in this manner until you say the variable type or return type.

So:

int (*x)[10];

x is a pointer to an array of 10 ints

int x[10];

x is an array of 10 ints

int *x[10];

x is an array of 10 pointers to ints

I tend to follow The Precedence Rule for Understanding C Declarations which is given very nicely in the book Expert C Programming - Deep C Secrets by Peter van der Linden

A - Declarations are read by starting with the name and then reading in 
precedence order.

B - The precedence, from high to low, is:
        B.1 parentheses grouping together parts of a declaration
        B.2 the postfix operators:
        parentheses () indicating a function, and
        square brackets [] indicating an array.
        B.3 the prefix operator: the asterisk denoting "pointer to".

C If a const and/or volatile keyword is next to a type specifier (e.g. int, 
        long, etc.) it applies to the type specifier. 
        Otherwise the const and/or volatile keyword 
        applies to the pointer asterisk on its immediate left.

For me, it's easier to remember the rule as absent any explicit grouping, () and [] bind before *. Thus, for a declaration like

T *a[N];

the [] bind before the *, so a is an N-element array of pointer. Breaking it down in steps:

   a     -- a
   a[N]  -- is an N-element array
  *a[N]  -- of pointer
T *a[N]  -- to T.

For a declaration like

T (*a)[N];

the parens force the * to bind before the [], so

    a      -- a
  (*a)     -- is a pointer
  (*a)[N]  -- to an N-element array
T (*a)[N]  -- of T

It's still the clockwise/spiral rule, just expressed in a more compact manner.

No. First one declares an array of 10 int pointers and second one declares an array of 10 ints.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!