Determinant
Determinant

Reputation: 4036

How to return a two-dimensional pointer in C?

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

xxxxxxx foo() {

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

BTW. I know that I must specify the size of one dimension at least, but how?

Upvotes: 12

Views: 12145

Answers (2)

John Bode
John Bode

Reputation: 123458

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].

Upvotes: 25

Paul R
Paul R

Reputation: 212939

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.

Upvotes: 19

Related Questions