C++ 数组大小依赖于函数参数导致编译错误 [英] C++ array size dependent on function parameter causes compile errors

查看:43
本文介绍了C++ 数组大小依赖于函数参数导致编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的函数,其中声明了一个数组的大小取决于参数是 int.

I have a simple function in which an array is declared with size depending on the parameter which is int.

    void f(int n){
        char a[n];
    };

    int main() {
        return 0;
    }

这段代码在 GNU C++ 上编译良好,但在 MSVC 上编译不正常2005.

This piece of code compiles fine on GNU C++, but not on MSVC 2005.

我收到以下编译错误:

    .\main.cpp(4) : error C2057: expected constant expression
    .\main.cpp(4) : error C2466: cannot allocate an array of constant size 0
    .\main.cpp(4) : error C2133: 'a' : unknown size

我能做些什么来纠正这个问题?

What can I do to correct this?

(我有兴趣使用 MSVC 完成这项工作,而不使用 new/delete)

(I'm interested in making this work with MSVC,without using new/delete)

推荐答案

您发现它是 Gnu 编译器对 C++ 语言的扩展之一.在这种情况下,Visual C++ 是完全正确的.C++ 中的数组必须定义为编译时常量表达式的大小.

What you have found it one of the Gnu compiler's extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression.

在 1999 年对 C 语言的更新中添加了一个特性,称为可变长度数组,这是合法的.如果能找到一个支持C99的C编译器,那可就不容易了.但此功能不是标准 C++ 的一部分,也不会在 C++ 标准的下一次更新中添加.

There was a feature added to C in the 1999 update to that language called variable length arrays, where this is legal. If you can find a C compiler that supports C99, which is not easy. But this feature is not part of standard C++, not is it going to be added in the next update to the C++ standard.

在C++中有两种解决方案.第一个是使用 std::vector,第二个是使用 operator new []:

There are two solutions in C++. The first is to use a std::vector, the second is just to use operator new []:

char *a = new char [n];

在我写答案时,另一个人发布了使用 _alloca 的建议.我强烈建议不要这样做.您只是将一种非标准、不可移植的方法替换为另一种与编译器相关的方法.

While I was writing my answer, another one posted a suggestion to use _alloca. I would strongly recommend against that. You would just be exchanging one non-standard, non-portable method for another one just as compiler-specific.

这篇关于C++ 数组大小依赖于函数参数导致编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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