我有这个方法:
void createSomething(Items &items)
{
int arr[items.count]; // number of items
}
但它抛出一个错误:
expression must have a constant value
我找到了这个解决方案:
int** arr= new int*[items.count];
所以我想问有没有更好的方法来处理这个问题?
您可以使用std::vector
void createSomething(Items &items)
{
std::vector<int> arr(items.count); // number of items
}
第一个方法不起作用的原因是必须在编译时知道数组的大小(不使用编译器扩展 https://stackoverflow.com/questions/737240/c-c-array-size-at-run-time-w-o-dynamic-allocation-is-allowed),所以你必须使用动态大小的数组。您可以使用new
自己分配数组
void createSomething(Items &items)
{
int* arr = new int[items.count]; // number of items
// also remember to clean up your memory
delete[] arr;
}
但使用a更安全,恕我直言更有帮助std::vector
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)