Vaibhav Kotnala
Vaibhav Kotnala

Reputation: 1

static memory allocation like dynamic memory allocation

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?

Upvotes: 0

Views: 436

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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.

Upvotes: 3

Rafaelplayerxd YT
Rafaelplayerxd YT

Reputation: 399

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.

Upvotes: 1

Related Questions