Trouble understanding C++ pointer syntax
May be you could just break it down one at a time to understand the syntax better. First start up with a simple definition without the array notation
int(*(*ptr)(char*));
So ptr
is a function pointer that takes a char
pointer as an argument and returns a pointer to an int
. Now extending it to the array notation
int(*(*ptr[3])(char*))[2];
which means you have an array of function pointers, each of which will take a char
pointer argument and return a pointer to an array of two integers.
You can see this working if you have a make a function call using these pointers you define. Note that, the below functions are for demonstrative purposes only and do not convey any logical purpose
#include <iostream>
static int arr[2] = { 2, 2 };
// initialize 'bar' as a function that accepts char* and returns
// int(*)[2]
int (*bar(char * str))[2] {
return &arr;
}
int main() {
// pointer definition, not initialized yet
int(*(*foo[3])(char*))[2];
char ch = 'f';
// as long as the signatures for the function pointer and
// bar matches, the assignment below shouldn't be a problem
foo[0] = bar;
// invoking the function by de-referencing the pointer at foo[0]
// Use 'auto' for C++11 or declare ptr as int (*ptr)[2]
auto *ptr = (*foo[0])(&ch);
return 0;
}
You have to unfold the type from the inside out and recall that []
and ()
(on the right) bind stronger than *
(on the left). To override this binding, parentheses ()
are used.
int(*(*ptr[3])(char*))[2];
^ ^ ^^ ^ ^ ^
| | || | | |
| | |ptr is | |
| | | | | |
| | | an array of three
| | | | |
| | pointers to |
| | | |
| | a function taking a char* and returning
| | |
| a pointer to |
| an array of two
ints
i.e. "ptr
is an array of three pointers to a function taking a char*
and returning a pointer to an array of two int
s".