无法理解 C++ 指针语法 [英] Trouble understanding C++ pointer syntax
问题描述
我无法理解我在面试中遇到的这段代码声明.
I'm not able to understand this statement of code that I came across during my interview.
int(*(*ptr[3])(char*))[2];
我曾尝试查看 IDE,但我所拥有的只是它是一个数据类型数组
I've tried looking at an IDE but all I have is that it is an array of data type
int (*(*[3])(char *))
我无法理解这一点.
推荐答案
也许你可以一次分解一个来更好地理解语法.首先从一个没有数组符号的简单定义开始
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*));
所以ptr
是一个函数指针,它接受一个char
指针作为参数并返回一个指向int
的指针.现在将其扩展为数组符号
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];
这意味着你有一个函数指针数组,每个函数指针都接受一个 char
指针参数并返回一个指向两个整数数组的指针.
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;
}
这篇关于无法理解 C++ 指针语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!