Trouble understanding C++ pointer syntax

自作多情 提交于 2021-02-18 23:01:47

问题


I'm not able to understand this statement of code that I came across during my interview.

int(*(*ptr[3])(char*))[2];

I've tried looking at an IDE but all I have is that it is an array of data type

int (*(*[3])(char *)) 

I wasn't able to understand this.


回答1:


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;
}



回答2:


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 ints".



来源:https://stackoverflow.com/questions/57602762/trouble-understanding-c-pointer-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!