Dealing with large arrays without getting runtime error

纵饮孤独 提交于 2019-12-02 20:31:37

问题


I am getting runtime error when I used array of size 10^5*10^5 (ex. int a[100000][100000]. As this array is consuming more memory, this may be one one of the reasons for runtime error.

How should I declare this array (2D array ex. int a[100000][100000]) so that I can cope with problem of SIGSEGV runtime error?

Please, provide approach to declare such type of array?


回答1:


Three ways to declare the large array int a[100000][100000] are:

  1. Make the large array global
  2. Make the large array static:

    static int a[100000][100000];
    
  3. Use malloc/calloc and dynamically allocate the large array:

    int **a;
    a=malloc(sizeof(int*)*100000);
    for(int i=0;i<100000;i++)
        a[i]=malloc(sizeof(int)*100000);
    
    /*Use the array*/
    
    for(int i=0;i<100000;i++)
        free(a[i]);
    free(a);
    


来源:https://stackoverflow.com/questions/29444371/dealing-with-large-arrays-without-getting-runtime-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!