简体   繁体   English

指针数组中的C ++错误

[英]C++ Error in array of pointers

I have a piece of code: 我有一段代码:

int CPUs = GetNumCPUs();
FILE *newFile[CPUs];

I got an error. 我有一个错误。 It marks 'CPUs' on the second line and says: "expression must have a constant value". 它在第二行上标记“ CPU”,并说:“表达式必须具有恒定值”。

I have tried to use const but it is not working. 我尝试使用const但是它不起作用。

You can't have a varible sized array in C++. C ++中不能有大小可变的数组。 Adding const to CPUs doesn't help, it only makes the variable read-only, but it's still not a compile time constant because it's initialized by a function at run-time. const添加到CPUs并没有帮助,它只会使变量成为只读变量,但仍不是编译时常量,因为它是在运行时由函数初始化的。

The usual solution is to use a vector: 通常的解决方案是使用向量:

std::vector<FILE*> newFile(CPUs);

The value of GetNumCPUs() may or may not change every time you run the program - so it is not constant. 每次运行程序时, GetNumCPUs()的值可能会更改,也可能不会更改-因此它不是常数。 If you want an array that has a variable amount of elements, try std::vector : 如果您想要一个具有可变数量元素的数组,请尝试std::vector

std::vector<FILE*> newFile(GetNumCPUs());

In your code, const doesn't mean "constant". 在您的代码中, const并不意味着“ constant”。 In this context, it means the object is read-only — ie you can't modify the object. 在这种情况下,这意味着该对象是只读的 ,即,您不能修改该对象。 You're trying to create a variable length array, which isn't allowed in C++. 您正在尝试创建一个可变长度的数组,这在C ++中是不允许的。 Use std::vector , use new to allocate memory, or write a C99 program where VLAs like the one you're trying to make are allowed. 使用std::vector ,使用new来分配内存,或编写一个C99程序,其中允许使用您要制作的VLA。

Using a const doesn't fix all of your problems in this scenario. 使用const不能解决这种情况下的所有问题。 The problem is that arrays must be initialized at compile time, so if you have a function return a variable ( GetNumCPUs() ) and assign it to a constant ( const int CPUs ), the variable isn't known at compile time but runtime, and the compiler can't allocate data space for the array. 问题在于数组必须在编译时初始化,因此,如果您有一个函数返回变量( GetNumCPUs() )并将其分配给常量( const int CPUs ),则该变量在编译时未知,但在运行时,并且编译器无法为数组分配数据空间。

Using an std::vector , however, allows for variable storage space. 但是,使用std::vector可以提供可变的存储空间。

std::vector<FILE*> newFile(CPUs);

This should work fine. 这应该工作正常。 Here's a couple tutorials: 这里有一些教程:

http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm

http://www.dreamincode.net/forums/topic/33631-c-vector-tutorial/ http://www.dreamincode.net/forums/topic/33631-c-vector-tutorial/

在编译时不知道CPU。

You should dynamically create the array with new[] 您应该使用new []动态创建数组

int CPUs = GetNumCPUs();
FILE** newFile = new (FILE*)[CPUs];

After you're done with it, you're now responsible for deleting it as well: 完成后,您现在还需要删除它:

delete[] newFile;

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

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