How to allocate and free memory for an array of structures, which in turn contains a two-dimensional (matrix) array? :

#define N 5000 #define DAYS 700 #define ChCount 500 struct Ch { int **Days; int Length; } RCh; int main (void) { Ch *RCh = new Ch[ChCount]; for (int i = 0; i<ChCount; i++) { RCh[i].Days = new int* [N]; for (int j = 0; j < N; j++) RCh[i].Days[j] = new int[DAYS]; } //операции с массивом RCh[N].Days[N][DAYS] delete[] RCh; } 

As a result, an error occurs:

Unhandled exception in "0x757ec6e3" in "data.exe": Microsoft C ++ Exception:

std :: bad_alloc at 0x00113744 ..

But if you use this entry:

 struct Ch { int Days[N][DAYS] int Length; } RCh; int main(void) { Ch *RCh; RCh = (Ch*)malloc(ChCount*sizeof(Ch)); } 

there are no problems, however, only for small numbers N (<1500).

    2 answers 2

    To allocate the amount of memory you want to allocate, you need a lot of operatives on the computer))

    Count how much memory you need for your numbers.

    5000 * 700 * 500 * sizeof (int) = number of bytes.
    number of bytes / 1024/1024/1024 = number of gigabytes of RAM
    I got 6.5 Gigov))

    So an exception pops up which says that it cannot allocate memory.

    • Thanks for the answer! )) - Fox

    You really want to highlight too much. The system cannot provide you with space for 1,750,000,000 int numbers. Personally, I managed to beg only 2 989 999.