我对下面附加的代码片段有疑问。不管怎样,我在 ideone.com 上运行了这段代码,得到了两个不同的结果
- C : 成功。
- C++ : 错误:
prog.cpp: In function ‘int main()’: prog.cpp:20:13: error: cannot convert ‘int* (*)[2][10]’ to \ ‘int* (*)[10]’ for argument ‘1’ to ‘void foo(int* (*)[10], size_t)’ foo(&a, LEN); ^
C++ 中的结果是我所期望的,但它在 C 中成功运行,而且它似乎依赖于编译器,因为聊天中帮助运行该代码段的人只收到警告。
那么我错过了哪一部分?是 C 自动做了一些转换吗?
#include <stdio.h>
#include <stddef.h>
#define LEN 2
void foo(int* a[][10], size_t len) {
printf("%s\n", "successfully called foo.");
}
int main(void) {
// a is an LEN-array of an 10-array of (int *)
int *a[LEN][10] = {{0}};
// but the identifier `a` will decay to be a pointer of type int*[10]
// p1 is a pointer to an 10-array of (int *)
int *(*p1)[10] = 0;
foo(a, LEN);
foo(&a, LEN);
return 0;
}
最佳答案
大刀阔斧的编辑;正如评论中指出的那样,之前的答案是错误的。
该程序在 C 和 C++ 中都是良构的。但是各个语言的标准不允许成功编译违反强加约束的程序。这允许实现扩展语言。实现仅需要发出诊断消息。警告和错误都是合规行为。
无论出于何种原因,您使用的编译器(通过 ideone)在编译 C++ 时选择了不同的行为。
关于c++ - 将指向数组的指针传递给 C 和 C++ 中的函数的两个不同结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53396900/