Difference between two declarations involving a pointer and an array

后端 未结 6 1253
臣服心动
臣服心动 2020-12-18 11:45

What is the difference between int *a[3] and int (*a)[3]?

6条回答
  •  被撕碎了的回忆
    2020-12-18 12:16

    There is an excellent article to be found at this URL on reading C type declarations. The author, Eli Bendersky, gives a simple method for reading the declarations. You start at the name of the variable and then move along the line pronouncing what you encounter as you walk along. The basic method is to start at the variable name and go right. I'll provide a simple overview, but I highly recommend you read the article.

    1. Start at the variable name and head right.
    2. If you hit a right paren ) or a semicolon ;, then turn back to where you started going right and then go left.
    3. If you encounter a left paren ( while going right, then you have encountered a function declaration, and what follows is its comma-separated list of arguments. Note: you will encounter a right paren at the end of the argument list. The above rule does not apply to this right paren.
    4. If you encounter a left bracket, read it as 'array'.
    5. After going left, when you hit a left paren (, then go back to the right paren where you last went right. Hop over that right paren, and then keep going repeat.
    6. [Repeat]

    So, in applying this rule to your particular problem...

    In the declaration, " int * a[3]; ", a is the variable name. So, it is read:

    a is an array ([) of 3 elements ([3]) of pointers (*) to integers (int)

    While in the declaration, " int (* a)[3]; ", a is the variable name. So, it is read:

    a is a pointer (*) to an array ([) of 3 elements ([3]) of integers (int)

提交回复
热议问题