Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a two-dimensional pointer in C?

Tags:

c

pointers

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?

like image 487
Determinant Avatar asked May 29 '12 07:05

Determinant


People also ask

Can you return a pointer in C?

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.

How do you return a two dimensional array?

Returning Two dimensional Array from a Method in Java. In the above syntax, the use of two pairs of square brackets indicates that the method returns two-dimensional array of type data-type. The general syntax of calling a method is as follows: data-type[ ][ ] arrayname = obj-ref.

How do you return the value of a pointer?

To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber . It is called dereferencing or indirection).

Can we return a 2D array from a function in C?

You can't pass arrays to or return arrays from functions in C, but you can pass/return pointers to them.


2 Answers

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

like image 109
John Bode Avatar answered Oct 21 '22 14:10

John Bode


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.

like image 18
Paul R Avatar answered Oct 21 '22 13:10

Paul R