【发布时间】:2019-02-08 22:38:58
【问题描述】:
是否可以在一个函数中从另一个函数向堆栈分配可变长度数组?
一种可行的方法是预先分配尽可能大的大小,但我想知道是否有办法避免这种情况。
void outside_function(){
char[] place_to_allocate_stack_array;
size_t array_size = allocate_and_fill_array(place_to_allocate_stack_array);
//do stuff with the now allocated variable length array on stack
}
size_t allocate_and_fill_array(char* place_to_allocate){
//does some stuff to determine how long the array needs to be
size_t length= determine_length();
//here I want to allocate the variable length array to the stack,
//but I want the outside_function to still be able to access it after
//the code exits allocate_and_fill_array
place_to_allocate[length];
//do stuff to fill the array with data
return length;
}
size_t determine_length(){
////unknown calculations to determine required length
}
【问题讨论】:
-
但我想知道是否有办法避免这种情况。
std::string和std::vector是避免这种情况的方法。 -
最新标准支持 vsa(编译器特性),但是有什么用呢?使用向量。避免这种跨功能的东西。
-
您无法调整堆栈中数组的大小。一旦你分配它,它就被分配了。
-
用std::vector,能保证所有的内存分配都在栈上吗?
-
这是一个可变长度数组。 many good reasons 的 C++ 标准不支持它们。一些编译器无论如何都允许它们。无论如何,一旦创建它就无法调整大小,因此您无法将其传递给函数并调整其大小。如果您在函数中创建它并调整它的大小,然后尝试将其交还给调用者,也无法返回。一般来说,原始数组很烂。他们很好地解决了 1970 年代的问题,但他们在 2010 年代的问题上表现不佳。
标签: c++ arrays variable-length-array