C++ Tutorial

There are a lot of application of dynamic memory allocation. In this article, I’m going to give a brief intuition so that, you may understand intuitively why dynamic memory allocation is important & fascinating in the programming world.

Let’s take a look at the following code

#include <iostream>
using namespace std;

int *ArrMul(int a[], int b[], int size) {

int *c = new int[size];

for (int i = 0; i < size; i++) {
c[i] = a[i] * b[i];
}

return c;
}

void printArray(int *arg, int length) {
for (int i = 0; i < length; i++) {
cout << *(arg + i) << endl;
}
}

int main()
{
int firstArray[5] = { 5, 10, 15, 20, 25 };
int secondArray[5] = { 2, 4, 6, 8, 10 };

int *z = NULL;

z = ArrMul(firstArray, secondArray, 5);

printArray(z, 5);

return 0;
}

Output:

10
40
90
160
250

 

I’m assuming you know the basic concept of function call & able to play with the array. That’s why I’m not explaining the code. If you still having problems to understand the code please let me know in the comment. I will try my best to make you understand.

In the following program look at line 6. In this line, you can see that I’ve allocated memory dynamically. 

If I wrote the syntax of line 6 as:

int c[size];

What do you think the program would print the exact same result?

No

Why?

Because when a function has executed, the variable (data) within the function is erased (deallocated) automatically & freed to used by other programs. So when the array is called without dynamic memory allocation this will give garbage value. Because by the time the address of C array is returned it’s deallocated. And the memory block reserved by this array is no longer holding its value in memory (RAM). So there is a higher potential that the address will hold another program value or garbage value without being the array allocated dynamically in the program.

But when I allocated the c array memory dynamically the value of array was still reserved in the memory after the function had executed & was able to assign in the main function pointer variable exactly.

Thanks for reading. Hope this article gave you an intuition about dynamic memory allocation & it’s application. Let me know your thoughts in the comment.

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.