c++ - 指向未指定大小的数组的指针 "(*p)[]"在 C++ 中是非法的,但在 C 中是合法的

标签 c++ c arrays function pointers

我刚刚发现这在 C++ 中是非法的(但在 C 中是合法的):

#include <stdio.h>
#include <stdlib.h>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))

int accumulate(int n, const int (*array)[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += (*array)[i];
    }
    return sum;
}

int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), &a));
    return 0;
}

使用 gcc -std=c89 -pedantic 编译没有问题,但使用 g++ 编译失败。当我尝试使用 g++ 编译它时,我收到以下错误消息:

main.cpp:5:37: error: parameter 'array' includes pointer to array of unknown bound 'int []'
 int accumulate(int n, int (*array)[])
                                     ^
main.cpp: In function 'int main()':
main.cpp:18:50: error: cannot convert 'int (*)[9]' to 'int (*)[]' for argument '2' to 'int accumulate(int, int (*)[])'
     printf("%d\n", accumulate(ARRAY_LENGTH(a), &a));

我已经在我的 C 代码中使用它很长时间了,但我不知道它在 C++ 中是非法的。对我来说,这似乎是一种有用的方法来记录一个函数采用一个事先不知道大小的数组。

我想知道为什么这是合法的 C 而无效的 C++。我还想知道是什么让 C++ 委员会决定取消它(并破坏与 C 的兼容性)。

那么为什么这个 C 代码是合法的,而 C++ 代码却是非法的呢?

最佳答案

Dan Saks wrote about this in 1995 ,在 C++ 标准化之前:

The committees decided that functions such as this, that accept a pointer or reference to an array with unknown bound, complicate declaration matching and overload resolution rules in C++. The committees agreed that, since such functions have little utility and are fairly uncommon, it would be simplest to just ban them. Hence, the C++ draft now states:

If the type of a parameter includes a type of the form pointer to array of unknown bound of T or reference to array of unknown bound of T, the program is ill-formed.

关于c++ - 指向未指定大小的数组的指针 "(*p)[]"在 C++ 中是非法的,但在 C 中是合法的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27897646/

相关文章:

c++ - 相似但不相同的代码模板?

ruby-on-rails - 如何将多级数组中的唯一值映射到 value=>array 的散列?

javascript - 迭代 DataTables Json 数据时的数组索引

java - Android Collection ,我应该使用哪个?

c - arm-none-eabi-gcc : Printing float number using printf

C++ Linux 命名管道卡在 open() 与 O_WRONLY

c++ - 如何在 C++ 模板函数中设置默认值?

c++ - 为什么这个针对给定挑战的解决方案不起作用?

c++ - delete my_object 时到底发生了什么;被执行? sizeof(MyClass) 是否将所有其他内存向左移动?

c - 如何检查c代码链表中的可用座位