c++ - 难以理解 C++ 指针语法

标签 c++ pointers declaration

我无法理解我在面试中遇到的这段代码声明。

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/

相关文章:

c++ - 平衡二叉搜索树 (BST)

c++ - 强制两个线程直接访问内存中的全局变量?

c - 在结构体中释放 char**

c++ - 如何理解取消引用指向数组的指针得到指向元素的指针?

c - "expected expression before char"内部函数

c - 在 C 函数的参数中声明变量

c++ - C++ 中 bool 函数没有引用参数?

c++ - 使用 boost 进程获取 shell 命令的标准输出

c - 如何动态改变char指针大小?

c++ - 如何修复二进制运算符