二维数组的分段错误 [英] segmentation fault for 2D arrays
本文介绍了二维数组的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想定义一个非常大的二维数组.但它给了我分段错误?
I want to define a 2D array of very big size. But it is giving me segmentation fault?
#include <stdio.h>
int main () {
int i;
int temp[4000][5000];
for (i = 0; i < 5; i++)
{
printf ("Hello World\n");
}
}
有人可以建议我其他方式吗?内存初始化有问题吗?提前致谢
Can anyone please suggest me some other way? Is there some problem with memory initialization? Thanks in advance
推荐答案
你可以只在一个数组中分配整个表,但你将无法使用两个方括号访问带有索引的数组数据:
You can allocate the whole table in only one array but you won't be able to access array data with indices using two square brackets:
int * temp = malloc(4000*5000*sizeof(int));
要访问之前编写 temp[i][j]
的元素 (i,j),现在应该按以下方式计算索引:
to access the element (i,j) where previously you wrote temp[i][j]
, now you should now compute the index the following way:
temp[i*5000+j];
并且不要忘记之后释放为您的表分配的内存:
and do not forget to free the memory allocated for your table afterward:
free(temp);
这篇关于二维数组的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文