传递指针,然后将可变长度数组分配给堆栈

Passing pointer and then allocating variable length array to stack

本文关键字:数组 分配 堆栈 指针 然后      更新时间:2023-10-16

是否可以从另一个函数向一个函数中的堆栈分配可变长度数组?

一种可行的方法是预先分配尽可能大的大小,但我想知道是否有办法避免这种情况。

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
}

尽管如此,这种对获取堆栈上的数据的痴迷可能还为时过早。虽然堆存储确实比堆栈存储更昂贵,但这种差异通常不值得担心。在跳过重重关卡调整性能之前,让你的程序正常工作。注重稳健性。只有在探查器识别出性能瓶颈后,才能在该瓶颈上花费时间。