How to return a two-dimensional pointer in C?

前端 未结 2 1091
感动是毒
感动是毒 2020-12-09 00:04

As the title suggests, how to return pointer like this:

xxxxxxx foo() {

    static int arr[5][5];
    return arr;
}

BTW. I know that I mus

相关标签:
2条回答
  • 2020-12-09 00:53

    The return type would be int (*)[5] (pointer to 5-element array of int), as follows

    int (*foo(void))[5]
    {
      static int arr[5][5];
      ...
      return arr;
    }
    

    It breaks down as

          foo             -- foo
          foo(    )       -- is a function
          foo(void)       --   taking no parameters
         *foo(void)       -- returning a pointer
        (*foo(void))[5]   --   to a 5-element array       
    int (*foo(void))[5]   --   of int
    

    Remember that in most contexts, an expression of type "N-element array of T" is converted to type "pointer to T". The type of the expression arr is "5-element array of 5-element arrays of int", so it's converted to "pointer to 5-element array of int", or int (*)[5].

    0 讨论(0)
  • 2020-12-09 01:01

    It helps to use a typedef for this:

    typedef int MyArrayType[][5];
    
    MyArrayType * foo(void)
    {
        static int arr[5][5];
        return &arr;   // NB: return pointer to 2D array
    }
    

    If you don't want a use a typedef for some reason, or are just curious about what a naked version of the above function would look like, then the answer is this:

    int (*foo(void))[][5]
    {
        static int arr[5][5];
        return &arr;
    }
    

    Hopefully you can see why using a typedef is a good idea for such cases.

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