Is this correct?
int (*(*ptr)())[];
I know this is trivial, but I was looking at an old test about these kind of constructs, and this particular combination wasn't on the test and it's really driving me crazy; I just have to make sure. Is there a clear and solid understandable rule to these kind of declarations? (ie: pointer to... array of.. pointers to... functions that.... etc etc) Thanks!
R
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
p = arr; // Points to the whole array arr. p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr. The base type of p is int while base type of ptr is 'an array of 5 integers'.
int foo(int); Here foo is a function that returns int and takes one argument of int type. So as a logical guy will think, by putting a * operator between int and foo(int) should create a pointer to a function i.e. int * foo(int);
int (*f) (int * ): A pointer to a function that takes an integer pointer as argument and returns an integer.
The right-left rule makes it easy.
int (*(*ptr)())[];
can be interpreted as
Start from the variable name ------------------------------- ptr
Nothing to right but )
so go left to find *
-------------- is a pointer
Jump out of parentheses and encounter ()
----------- to a function that takes no arguments(in case of C unspecified number of arguments)
Go left, find *
------------------------------------------------ and returns a pointer
Jump put of parentheses, go right and hit []
---------- to an array of
Go left again, find int
------------------------------------- ints
.
In almost all situations where you want to return a pointer to an array the simplest thing to do is to return a pointer to the first element of the array. This pointer can be used in the same contexts as an array name an provides no more or less indirection than returning a pointer of type "pointer to array", indeed it will hold the same pointer value.
If you follow this you want a pointer to a function returning a pointer to an int
. You can build this up (construction of declarations is easier than parsing).
Pointer to int
:
int *A;
Function returning pointer to int
:
int *fn();
pointer to function returning a pointer to int
:
int *(*pfn)();
If you really want to return a pointer to a function returning a pointer to an array of int
you can follow the same process.
Array of int:
int A[];
Pointer to array of int:
int (*p)[];
Function returning pointer ... :
int (*fn())[];
Pointer to fn ... :
int (*(*pfn)())[];
which is what you have.
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