C++ Tutorial

There are lots of applications of dynamic memory allocation in programming. In this tutorial, I’m going to discuss an interesting application of dynamic memory allocation.

Have you ever wondered why you can’t use a variable for an array size in C++?

Well, you can! In CodeBlocks, you can use a variable for an array size. Actually, it’s GCC compiler which allows the scenario. Since GCC compiler is default compiler in CodeBlocks. CodeBlocks allow using a variable for an array size. But unfortunately, this is not the standard of C++.

Probably you have used the following syntax in C/C++ language to declare an array:

int arr[variable];

But unfortunately, this syntax of allocating memory for the array was declared illegal by the C++ standard committee & in the ’90s they decided not to allow it.

If you don’t believe me, you may try to use this syntax ” int arr[variable]; ” in Microsoft VS. It will show you a message like “expression must have a constant value“.

dynamic allocation

Why this problem arises?

Well In C++, the compiler must know the amount of memory to allocate for an array at compile time. However, the size of a variable is unknown until the runtime. This is why you’re not allowed to use a variable as the array size.

How do we solve this problem?

Like every problem, this problem has a solution which I found interesting & want to share it with you.

Instead of using the previous syntax, you have to use the following syntax so that Dynamic memory allocation is held in your program:

int *arr = new int[variable];

For instance, consider the following program:

#include <iostream>
using namespace std;


int main() {
	int n, i;
	cin >> n;

	int *var = new int[n];

	for (i = 0; i < n; i++) {
		var[i] = i;
		cout << var[i] << endl;
	}

    delete[]var;

	return 0;
}

In this program, I created a pointer named “var”. Then with the help of this pointer, I wrote my program & allocated memory for the array dynamically.

cpp dynamic allocation

Now there will be no error in the program as I’ve allocated the memory dynamically with appropriate syntax.

You can use this concept to create any kind of array (ex: an array of object).

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.