Equivalent C declarations

前端 未结 5 1485
南笙
南笙 2021-02-04 20:18

Are

int (*x)[10];

and

int x[10];

equivalent?

According to the \"Clockwise Spiral\" rule, they parse

相关标签:
5条回答
  • 2021-02-04 20:59

    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.

    0 讨论(0)
  • 2021-02-04 21:00

    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.

    0 讨论(0)
  • 2021-02-04 21:03

    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.
    
    0 讨论(0)
  • 2021-02-04 21:10

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

    0 讨论(0)
  • 2021-02-04 21:16

    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

    0 讨论(0)
提交回复
热议问题