How to work with large 2D arrays

I have a 5428x5428 2D array. This is a symmetric array. but when compiling it gives me an error saying that the size of the array is too large. can anyone provide me a way?

+3
source share
3 answers

This array is large for the memory of the program stack - this is your mistake.

int main()
{
    double arr[5428][5428]; // 8bytes*5428*5428 = 224MB

    // ...
    // use arr[y][x]
    // ...

    // no memory freeing needed
}

Use dynamic array allocation:

int main()
{
    int i;
    double ** arr;

    arr = (double**)malloc(sizeof(double*)*5428);
    for (i = 0; i < 5428; i++)
        arr[i] = (double*)malloc(sizeof(double)*5428);

    // ...
    // use arr[y][x]
    // ...

    for (i = 0; i < 5428; i++)
        free(arr[i]);
    free(arr);
}

Or select a simple size array MxNand useptr[y*width+x]

int main()
{
    double * arr;
    arr = (double*)malloc(sizeof(double)*5428*5428);

    // ...
    // use arr[y*5428 + x]
    // ...

    free(arr);
}

Or use the combined method:

int main()
{
    int i;
    double * arr[5428];  // sizeof(double*)*5428 = 20Kb of stack for x86
    for(i = 0; i < 5428; i++)
        arr[i] = (double)malloc(sizeof(double)*5428);

    // ...
    // use arr[y][x]
    // ...

    for(i = 0; i < 5428; i++)
        free(arr[i]);
}
+3
source

When arrays become large, there are a number of solutions. The one that is good for you depends heavily on what you are actually doing.

I have listed a few for you to think:

  • Buy more memory.

  • .

    , .

  • ( , , 1/2 ).

    , " "

    int getArray(array, col, row);
    void setArray(array, col, row, value);

    array - , . getArray (..) , , , ( getArray(array, row, col);. .

  • , ( -) " , "

    , ( ) . , - "" , " " , , "" .

- , .

+1

, . .

, , , .. . . , k06a; malloc() - (, GlobalAlloc() Windows). -, , .

Using global or static has the disadvantage that this memory will be allocated for the entire life of your program. In addition, almost everyone hates global strategies. On the other hand, you can use the syntax of a two-dimensional array "array [x] [y]", etc. To access the elements of the array ... easier than making the array [x + y * width], plus you need to remember whether you should do "x + y * width" or "x * height + y".

+1
source

All Articles