将指针数组传递给C和C ++中的函数有两种不同的结果?

时间:2018-11-20 15:59:54

标签: c++ c

我对以下所附的代码段有疑问。无论如何,我在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;
}

2 个答案:

答案 0 :(得分:4)

这在C语言中无效。将gcc与-Wall -Wextra一起使用时,将输出以下内容:

x1.c: In function ‘main’:
x1.c:19:9: warning: passing argument 1 of ‘foo’ from incompatible pointer type [-Wincompatible-pointer-types]
     foo(&a, LEN);
         ^
x1.c:5:6: note: expected ‘int * (*)[10]’ but argument is of type ‘int * (*)[2][10]’
 void foo(int* a[][10], size_t len) {
      ^~~

类型不兼容。它仅显示为警告,因为C倾向于允许各种指针转换,即使它们不合适。

您可以执行以下操作:

int *(*p1)[10] = a;

foo(a, LEN);
foo(p1, LEN);

答案 1 :(得分:4)

严厉编辑;评论中指出,先前的答案是错误的。

该程序在C和C ++中都格式错误。但是,相应语言的标准不允许成功编译违反强加约束的程序。这允许实现扩展语言。仅需要执行即可发出诊断消息。警告和错误都是一致的行为。

无论出于何种原因,您使用的编译器(通过ideone)选择了在编译C ++时表现不同的行为。