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

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

问题描述

我需要声明一个全局大数组.我尝试使用 malloc out ouf main:

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天全站免登陆