传递指针,然后将可变长度数组分配给堆栈
Passing pointer and then allocating variable length array to stack
是否可以从另一个函数向一个函数中的堆栈分配可变长度数组?
一种可行的方法是预先分配尽可能大的大小,但我想知道是否有办法避免这种情况。
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
}
没有,甚至忽略了人们对使用可变长度数组(VLA)的担忧。你试图在一个单一的功能中完成太多。退后一步,看看你在问什么。
为了保持一致性并远离数组,我将重命名一些东西。考虑一下这个版本的设置:
class X; // instead of "char []" so we can drop the VLA baggage
size_t inner_function(X & data) { // was "allocate_and_fill_array"
// Determine how data should be allocated
// Do stuff with data
}
void outer_function() {
X data;
size_t data_size = inner_function(data);
}
需求#1:内部函数需要访问外部函数中声明的变量。这需要将变量作为参数传递给内部函数。这反过来要求在声明变量之后调用内部函数。
需求#2:内部函数确定应如何分配data
(在声明时发生)。这要求在声明变量之前调用内部函数。
这些要求具有相互矛盾的先决条件。不可能。
我被引导到一个问题:是什么引导你采取这种方法?您已经编写了一个单独的determine_length
函数。让outside_function
调用它,声明VLA,然后将VLA和长度传递给内部函数。概念上要简单得多。
size_t determine_length() {
// unknown calculations to determine required length
}
void fill_array(char* stack_array, size_t length) {
//do stuff to fill the array with data
}
void outside_function(){
size_t length = determine_length();
char stack_array[length];
fill_array(stack_array, length);
//do stuff with the variable length array on stack
}
尽管如此,这种对获取堆栈上的数据的痴迷可能还为时过早。虽然堆存储确实比堆栈存储更昂贵,但这种差异通常不值得担心。在跳过重重关卡调整性能之前,让你的程序正常工作。注重稳健性。只有在探查器识别出性能瓶颈后,才能在该瓶颈上花费时间。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 如何通过 malloc 为队列数组分配内存?
- 具有动态数组分配的OpenMP嵌套循环
- 如何为数组结构的数组分配内存
- 如何为结构数组分配内存?
- cpp 数组 - 分配常量索引有效,而非常量索引不起作用
- 如何为字符指针数组分配内存?
- 在 C++ 中初始化后的数组分配
- 将数据分配给了数组分配,但程序显示了以缓冲区超支的输出
- C++函数问题中的数组分配
- 子数组分配:使用聚合对象错误的预期"{...}"进行初始化
- 为什么我的指针数组分配不起作用
- std::堆栈和堆栈溢出错误的数组分配
- 在 c++ 中是否有通过声明"implicit"数组分配?
- 在 c++ 中为 2-D "Dynamically Created"数组分配值时遇到问题
- 如何为C++数组分配指向第一个元素的指针
- 字符数组分配
- 将数组分配在固定数量的线程之间
- 为构造函数中的数组分配值