asr*_*ama 6 c++ pointers declaration
我无法理解我在面试中遇到的这段代码声明。
int(*(*ptr[3])(char*))[2];
Run Code Online (Sandbox Code Playgroud)
我试着看一个IDE,但是我所拥有的只是它是数据类型的数组
int (*(*[3])(char *))
Run Code Online (Sandbox Code Playgroud)
我不明白这一点。
也许您可以一次将其分解以更好地理解语法。首先从一个没有数组符号的简单定义开始
int(*(*ptr)(char*));
Run Code Online (Sandbox Code Playgroud)
所以ptr是一个函数指针,需要一个char指针作为参数,并返回一个指针int。现在将其扩展为数组符号
int(*(*ptr[3])(char*))[2];
Run Code Online (Sandbox Code Playgroud)
这意味着您有一个函数指针数组,每个函数指针都将带有一个char指针参数,并返回一个指向两个整数数组的指针。
如果使用定义的这些指针进行函数调用,则可以看到此方法有效。请注意,以下功能仅用于说明目的,不传达任何逻辑目的
#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;
}
Run Code Online (Sandbox Code Playgroud)