c - 你将如何在 C 中声明一个二维指针数组?

标签 c arrays multidimensional-array function-pointers

...不使用 typedef。

我的老板声称他曾经在一次面试中被问到这个问题,当他给出答案时,面试官告诉他他不能使用 typedef,因为它的风格很差。

无论如何,他喜欢向人们抛出问题,看看他们是否能答对,通常是在新程序员午餐会上。没有人能做对(尤其是手边没有笔和纸或电脑)。下次他试图用它难倒某人时,我想做好准备 >:D

最佳答案

指向什么的二维数组?

T *p[N][M];     // N-element array of M-element array of pointer to T
T (*p[N][M])(); // N-element array of M-element array of pointer to 
                // function returning T

如果我们讨论的是指向二维数组的指针,那么事情只会变得稍微有趣一点:

T a[N][M];            // N-element array of M-element array of T
T (*p)[M] = a;        // Pointer to M-element array of T
T (**p2)[M] = &p;     // Pointer to pointer to M-element array of T
T (*p3)[N][M] = &a;   // Pointer to N-element array of M-element 
                      // array of T
T (**p4)[N][M] = &p3; // Pointer to pointer to N-element array of 
                      // M-element array of T

编辑:等等,我想我可能得到了你想要的。

T *(*a[N])[M];        // a is an N-element array of pointer to M-element
                      // array of pointer to T

编辑:现在我们真的很傻:

T *(*(*a)[N])[M];     // a is a pointer to an N-element array of 
                      // pointer to M-element array of pointer to T

T *(*(*(*f)())[N])[M];  // f is a pointer to a function returning
                        // a pointer to an N-element array of pointer
                        // to M-element array of pointer to T

T *(*(*f[N])())[M];     // f is an N-element array of pointer to 
                        // function returning pointer to M-element 
                        // array of pointer to T

对于病态的精神错乱者:

T *(*(*(*(*(*f)())[N])())[M])(); // f is a pointer to a function 
                                 // returning a pointer to a N-element
                                 // array of pointer to function 
                                 // returning M-element array of
                                 // pointer to function returning
                                 // pointer to T

Typedef 是给胆小鬼用的。

关于c - 你将如何在 C 中声明一个二维指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1136146/

相关文章:

c - 在 printf 参数中提升类型是否危险?

c - 使用 volatile 关键字修改 const 变量

c - 使用 SQLite3 和 C 的段错误

python - 增加 numpy 矩阵中的元素也会影响不同的矩阵和不相关的行

java - 使用Java的DeleteZero

python - 如何从 numpy 数组构造一个 ndarray? Python

c - 为什么我们不两次引用 char 指针数组?

javascript - 返回值作为对象属性

java - 将数组转换为多维数组 - Java

java - 出界多维数组在哪里