使用main之外的malloc [英] use malloc out of main

查看:110
本文介绍了使用main之外的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要声明一个全局大数组. 我试图在主目录中使用malloc:

I need to declare a global big sized array. I tried to use malloc out ouf main:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 200000

double *u_data = malloc(LENGTH * sizeof(double));
double *u_data_old = malloc(LENGTH * sizeof(double));
double *psi = malloc(LENGTH * sizeof(double));

void main(void){

    free(u_data);
    free(u_data_old);
    free(psi);
}

但是我收到此错误:初始化元素不是恒定的. 有人知道如何解决这个问题吗?

but I receive this error: initialiser element is not constant. Does anyone know how to solve this problem?

推荐答案

在C中,执行从main函数开始,并且在此之前没有运行动态全局初始化器的机制(与C ++不同).这意味着全局变量只能使用编译时常量表达式进行初始化,而不能使用需要动态确定的值进行初始化.

In C, execution begins at the main function, and there is no mechanism to run dynamic global initializers before that (unlike in C++). This means that global variables can only be initialized with compile-time constant expressions, but not with values that need to be determined dynamically.

简单的答案是,您的malloc调用应移至main函数中.

The simple answer is that your malloc calls should move into the main function.

void * p;
int main() {
    p = malloc(X);
    // ...
    free(p);
}

但是,这甚至可能不是必需的.如果您想要固定的空间量,则可以简单地定义一个全局数组:

However, this may not even be necessary. If you want a fixed amount of space, you can simply define a global array:

double data[HUGE];

int main() {
    // ...
}

此数组具有静态存储持续时间(与局部变量的自动存储持续时间相反),并且几乎没有静态存储的大小限制.实际上,用于全局对象的内存已经在程序加载时被预留了,它根本不是动态管理内存的一部分.

This array has static storage duration (as opposed to the automatic storage duration of local variables), and there are virtually no size restrictions of static storage. Practically, the memory for global objects is set aside already at program load time, and it is not part of the dynamically managed memory at all.

这篇关于使用main之外的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆