C:如何管理大型结构?

use*_*688 5 c heap structure

在C:

我试图使用包含大数组的结构,并在声明它时发生堆栈溢出错误.我猜(正确吗?)我在堆栈中没有足够的内存,因此,我应该使用堆(我不想改变我的堆栈内存大小,因为代码将由其他人使用).有人能告诉我一个简单的方法吗?或者我应该使用除结构之外的其他东西?

我的代码 - definitions.h:

#define a_large_number 100000

struct std_calibrations{
    double E[a_large_number];
};
Run Code Online (Sandbox Code Playgroud)

我的代码 - main.c:

int main(int argc, char *argv[])
{
    /* ...
    */

    // Stack overflows here:
    struct std_calibrations calibration;

    /* ...
    */

    return (0);
} 
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

Car*_*rum 7

有两种选择:

  1. 使用malloc(3)free(3)在运行时动态分配结构.当你说"应该使用堆"时,你正在谈论这个选项.

    struct std_calibrations *calibration = malloc(sizeof *calibration);
    
    Run Code Online (Sandbox Code Playgroud)

    然后,

    free(calibration);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 给结构静态存储持续时间.添加static关键字或使其成为全局关键字.这个选项可能会改变一些关于如何使用结构的语义,但是考虑到你的示例代码,它应该没问题.