How to return a two-dimensional pointer in C?

前端 未结 2 1100
感动是毒
感动是毒 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 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.

提交回复
热议问题