Figuring out C Declarations like: double (*b)[n]

前端 未结 4 1548
执笔经年
执笔经年 2020-12-31 04:48

I\'m trying to figure out some C declarations. What is the meaning of these C declarations?

double (*b)[n];
double (*c[n])();
double (*d())[n];
4条回答
  •  清酒与你
    2020-12-31 05:44

    Let try this way.

    first, you should be familiar with these three symbols:

    1. *  -- a pointer.
    2. [] -- an array.
    3. () -- a function.(notice: not parentheses)

    we take "double (*d())[n]" as an example.

    the first step is to find out the identifier in the declaration, an identifier is the name of variable, here it is "d".

    (i)
    -- what is "d"?
    ------------------------------------------------------------------------
    look to the right side of the identifier, to see if there is a "[]" or a "()" :
    ...d[]...: d is an array.
    ...d()...: d is a function.
    
    if neither, look to the left side, to see if there is a "*" :
    ...*d...: d is a pointer.
    ------------------------------------------------------------------------

    now we've found that d is a function. use x to replace d(), then the declaration becomes "double (*x)[n]"

    (ii)
    -- what is "x"?
    ------------------------------------------------------------------------
    repeat (i), we find that x is a pointer.
    that means, d is a function returning a pointer.
    ------------------------------------------------------------------------

    use y to replace *x, then the declaration becomes "double y[n]"

    (iii)
    -- what is "y"?
    ------------------------------------------------------------------------
    repeat (i), we find that y is an array of n elements.
    that means, d is a function returning a pointer to an array of n elements.
    ------------------------------------------------------------------------

    use z to replace y[n], then the declaration becomes "double z"

    (iv)
    -- what is "z"?
    ------------------------------------------------------------------------
    repeat (i), we find that z is a double.
    that means, d is a function returning a pointer to an array of n double elements.
    ------------------------------------------------------------------------

    let's see another expression:

    void (*(*f)(int)[n])(char)
    1.
      we find f.
    2.
      f is a pointer. *f -> a
      void (*a(int)[n])(char)
    3.
      a is a function. a() -> b
      void (*b[n])(char)
      --f is a pointer to a function (with an int parameter)--
    4.
      b is an array. b[] -> c
      void (*c)(char)
      --f is a pointer to a function returning an array (of n elements)--
    5.
      c is a pointer. *c -> d
      void d(char)
      --f is a pointer to a function returning an array of n pointers--
    6.
      d is a function returning void.
      --f is a pointer to a function returning an array of n pointers to functions (with a char parameter) returning void--

提交回复
热议问题