指向未指定大小的数组“(*p)[]"的指针;在 C++ 中非法但在 C 中合法 [英] Pointer to array of unspecified size "(*p)[]" illegal in C++ but legal in C

查看:26
本文介绍了指向未指定大小的数组“(*p)[]"的指针;在 C++ 中非法但在 C 中合法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just found out that this is illegal in C++ (but legal in 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++ 编译它时,我收到以下错误消息:

It compiles without problems using gcc -std=c89 -pedantic but fails to compile using g++. When I try to compile it using g++ I get these error messages:

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++ 中是非法的.对我来说,这似乎是一种有用的方式来记录一个函数接受一个事先未知大小的数组.

I have been using this in my C code for a long time and I had no idea that it was illegal in C++. To me this seems like a useful way to document that a function takes an array whose size is not known before hand.

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

I want to know why this is legal C but invalid C++. I also wonder what it was that made the C++ committee decide to take it away (and breaking this compatibility with C).

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

So why is this legal C code but illegal C++ code?

推荐答案

Dan Saks1995 年写了这个,在 C++ 标准化的准备阶段:

Dan Saks wrote about this in 1995, during the lead up to C++ standardisation:

委员会决定接受这样的职能指向未知边界的数组的指针或引用,复杂化C++ 中的声明匹配和重载解析规则.这委员会一致认为,由于这些功能几乎没有效用,而且是相当罕见的,最简单的方法是禁止它们.因此,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:

如果参数的类型包括表单指针的类型T 的未知边界数组或对未知边界数组的引用T,程序格式错误.

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.

这篇关于指向未指定大小的数组“(*p)[]"的指针;在 C++ 中非法但在 C 中合法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆