我无法理解我在面试中遇到的这段代码声明。
int(*(*ptr[3])(char*))[2];
我试过查看一个 IDE,但我所拥有的只是它是一个数据类型的数组
int (*(*[3])(char *))
我无法理解这一点。
最佳答案
或许您可以一次分解一个,以便更好地理解语法。首先从一个没有数组符号的简单定义开始
int(*(*ptr)(char*));
所以 ptr
是一个函数指针,它接受一个 char
指针作为参数并返回一个指向 int
的指针。现在将其扩展为数组表示法
int(*(*ptr[3])(char*))[2];
这意味着您有一个函数指针数组,每个函数指针都接受一个 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;
}
关于c++ - 难以理解 C++ 指针语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57602762/