C ++数组的大小依赖于功能参数的原因编译错误 [英] C++ array size dependent on function parameter causes compile errors

查看:282
本文介绍了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;
    }

这件code编译的在 GNU C ++ 的罚款,但不是在2005年MSVC。

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这项工作,而无需使用新的/删除)

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

推荐答案

您已经找到了它的GNU编译器的扩展C ++语言之一。在这种情况下,可视C ++是完全正确的。在C ++中数组必须用一个大小是一个编译时间常数前pression来定义。

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的功能。如果你能找到一个C编译器支持C99,这是不容易的。但是,此功能不是标准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 ::向量,二是只使用操作符新[]

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天全站免登陆