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/29055929/

相关文章:

c++ - 如何将 "add"用户自定义格式标志转为 basic_ostream?

c++ - 使用 std::runtime_error 而不是 CException

c++ - 为什么在 Ubuntu 18.04.1 的 netinet 中没有定义 in_addr6?

c - 创建邻接矩阵时出现问题

javascript - 程序到 2D Array 复杂对齐

arrays - Typescript 参数 - 通用对象数组和对象键数组(部分)

c++ - 自 1970 年以来,如何获取 C++ 中的当前时间戳?

c++ - Python bool 转换为 C++ (pybind11)

c - 如何使用 char** ? (指向字符数组的指针)

javascript - 通过对象数组中的值为对象分配等级