How to return a two-dimensional pointer in C?

As the name implies, how to return a pointer as follows:

xxxxxxx foo() { static int arr[5][5]; return arr; } 

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

+6
source share
2 answers

This helps to use 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 to use typedef for any reason or are just interested in what the bare version of the above function looks like, then the answer is:

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

Hope you can understand why using typedef is a good idea for such cases.

+10
source

The return type will be int (*)[5] (a pointer to a 5-element int array), as shown below:

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

It breaks into

  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 a type of "pointer to T ". The expression type arr is β€œa 5-element array of 5-element int arrays”, so it is converted to β€œpointer to a 5-element array int " or int (*)[5] .

+9
source

Source: https://habr.com/ru/post/916884/


All Articles