在 C 中创建大型数组 [英] Creating large arrays in C

查看:70
本文介绍了在 C 中创建大型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与C语言有关.我必须创建一个包含大约 200 万个元素的大数组,但计算机给出了分段错误(核心转储)"错误.我只想说:

My question is related to C language. I have to create a big array of around two million elements but the computer gives a "Segmentation fault (Core dumped)" error. I am simply saying:

int integer_array[2000000];
float float_array[2000000];

我确定这与分配给数组的内存有关,但我无法找出正确的解决方案.

I am sure this has something to do with the memory allocated to arrays but I cannot figure out the right solution.

推荐答案

通常你需要在堆上动态创建这样的数组.

Usually you need to create such an array dynamically on the heap.

int *integer_array = (int*)malloc(2000000 * sizeof(int));
float *float_array = (float*)malloc(2000000 * sizeof(float));

对于堆栈分配,数组可能太大,例如如果不是全局使用,而是在函数内部使用.

The array might be too large for stack allocation, e.g. if used not globally, but inside a function.

int main () {
    int a[200000000]; /* => SEGV */
    a[0]=0;
}

最简单的解决方法,将数组移到外面:

The easiest fix, move the array outside:

int a[200000000];
int main () {
    a[0]=0;
}

您也可以将其声明为静态:

You can also declare it static:

int main () {
    static int a[200000000];
    a[0]=0;
}

请注意,堆栈大小取决于系统.可以使用 ulimit 更改它.

Note that the stack size is system dependent. One can change it with ulimit.

这篇关于在 C 中创建大型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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