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?
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.
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.
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).
You can't pass arrays to or return arrays from functions in C, but you can pass/return pointers to them.
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]
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With