相关疑难解决方法(0)

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

我刚刚发现这在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;
}
Run Code Online (Sandbox Code Playgroud)

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

main.cpp:5:37: error: parameter 'array' includes pointer to array of unknown bound …
Run Code Online (Sandbox Code Playgroud)

c c++ arrays pointers function

33
推荐指数
2
解决办法
4926
查看次数

标签 统计

arrays ×1

c ×1

c++ ×1

function ×1

pointers ×1