Home > Blockchain >  static memory allocation like dynamic memory allocation
static memory allocation like dynamic memory allocation

Time:03-14

Code:

int r, c;
cin >> r >> c;
int matrix[r][c];

I don't understand the idea behind runtime allocation. The aim is to allocate memory during runtime but in the above section of code we are doing the same.

When this part of code is run, the inputs sizes are given during runtime and matrix is allocated memory according to the size of rows and columns, so how is it static or compile time allocation?

CodePudding user response:

This declaration

int r, c;
cin >> r >> c;
int matrix[r][c];

is a declaration of a variable length array.

This array has automatic storage duration. And the array is created at run-time when the values of the variables r and c will be known.

However variable length arrays are not a standard C feature.

Instead of the array you could use the standard container std::vector like

std::vector<std::vector<int>> matrix( r, std::vector<int>( c ) );

In this case all elements of the matrix will be zero-initialized.

CodePudding user response:

Static but allocated at runtime.

Static allocation is fixed size and occurrs on the fast but small stack:

int a = 0;

Dynamic allocation can be dynamically sized but it is not performat to allocate small thing on the heap:

int* a = new int(0);

Only dynamic memory can be passed to different scopes but you need to delete it when you're done.

  • Related