简体   繁体   English

2D阵列分割错误

[英]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));

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][j]的元素(i,j),现在您应该通过以下方式计算索引:

temp[i*5000+j];

and do not forget to free the memory allocated for your table afterward: 并且不要忘记以后释放为表分配的内存:

free(temp);
int temp[4000][5000];

That's a VERY BIG array, way bigger than the normal size of stack, you get a segmentation fault because of stack overflow . 那是一个非常大的数组,比正常的堆栈大得多,由于堆栈溢出 ,您会遇到分段错误。 Consider using dynamic allocation instead. 考虑改用动态分配。

You need to use dynamic allocated arrays for such big arrays. 您需要为这样的大数组使用动态分配的数组。

Try: 尝试:

int* temp[4000];
for(i = 0; i < 4000; ++i) temp[i] = malloc(5000 * sizeof(int));
...
for(i = 0; i < 4000; ++i) free(temp[i]).

Whole program with error checking: 带有错误检查的整个程序:

int main () {
    int i, j;
    int* temp[4000];
    for (i = 0; i < 4000; ++i)
    {
        temp[i] = malloc(5000 * sizeof(int));
        if (temp[i] == NULL)
        {
            for (j = 0; j < i; ++j) free(temp[i]);
            exit(1);
        }
    }
    for (i = 0; i < 5; i++)
    {
        printf ("Hello World\n");
    }

    for (i = 0; i < 4000; ++i) free(temp[i]);
}

Here you can find function which would use single malloc call to allocate two dimension array. 在这里,您可以找到使用单个malloc调用分配二维数组的函数。

And simpler version of my own: 和我自己的更简单的版本:

int main () {
    int i, j;
    int* temp[4000];
    int* array = malloc(4000 * 5000 * sizeof(int));
    if (malloc_tmp == NULL) exit(1);
    for (i = 0; i < 4000; ++i)
    {
        temp[i] = array + (i * 5000);
    }
    for (i = 0; i < 5; i++)
    {
        printf ("Hello World\n");
    }

    free(temp[0]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM