简体   繁体   English

使用visual C ++编译器(Visual Studio 2010)导致变量数组大小出错。如何规避这个问题?

[英]Error with variable array size using the visual C++ compiler (Visual Studio 2010). How to circumvent this issue?

I am experiencing some troubles compiling a c++ file that worked well as a previous build under GCC. 我遇到了一些编译c ++文件的麻烦,该文件在GCC下作为以前的版本运行良好。 The issue is, I am using vectors of variable array size: 问题是,我使用的是变量数组大小的向量:

unsigned int howmany;
std::vector<int>* array_adresses[howmany]; 

I am currently using the Visual-Studio 2010 C++ compiler to built Matlab 64-bit Mex-Files. 我目前正在使用Visual-Studio 2010 C ++编译器来构建Matlab 64位Mex文件。 Since VC++ won't allow me to use arrays whose size is unknown at compile time, I am receiving the following error messages: 由于VC ++不允许我在编译时使用大小未知的数组,因此我收到以下错误消息:

error 2057: constant expression expected error 2466: error 2133: unknown size 错误2057:常量表达式预期错误2466:错误2133:未知大小

Is there any way to build the 64 bit mex file using a GCC-compiler option or build it with a different 64-bit compiler under Matlab? 有没有办法使用GCC编译器选项构建64位mex文件,或者在Matlab下使用不同的64位编译器构建它?

Thanks in advance!! 提前致谢!!

howmany needs to be constant, and needs to be a defined amount, like so: howmany需要保持不变,并且需要是一个定义的数量,如下所示:

const unsigned int howmany = 5;
std::vector<int>* array_adresses[howmany];

Or you can define it dynamically like this: 或者您可以像这样动态定义它:

unsigned int howmany = 5;
std::vector<int>* array_adresses = new std::vector<int>[howmany];

C++ standard doesn't allow variable-length arrays. C ++标准不允许使用可变长度数组。 Lets take this code: 让我们拿这个代码:

int main(int argc, char *argv[])
{
    int a[argc];
    return 0;
}

This compiles fine with g++ foo.cpp , but fails if you require a strict standard compliance. 这与g++ foo.cpp编译良好,但如果您需要严格的标准合规性, g++ foo.cpp失败。

g++ foo.cpp -std=c++98 -pedantic : g++ foo.cpp -std=c++98 -pedantic

foo.cpp: In function ‘int main(int, char**)’:
foo.cpp:8: warning: ISO C++ forbids variable length array ‘a’

You should use vector<vector<int> *> or vector<int> ** instead as others already suggested. 您应该使用vector<vector<int> *>vector<int> **而不是已经建议的其他人。

Simply replace int ptr[howmany]; 只需替换int ptr [howmany]; with vector ptr(howmany); 与矢量ptr(howmany);

to obtain also automatic deallocation at the end of the scope 在范围的最后获得自动释放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM