Dynamically Allocating Arrays
The major use of the concept of dynamic memory allocation is for allocating memory to an array when we have to declare it by specifying its size but are not sure about it.
Let’s see examples to understand its usage.
#include <iostream>
using namespace std;
int main()
{
int len, sum = 0;
cout << "Enter the no. of students in the class" << endl;
cin >> len;
int *marks= new int [len]; //Dynamic memory allocation
OR
int *marks = (int*)malloc(len * sizeof(int)); //Dynamic memory allocation
cout << "Enter the marks of each student" << endl;
for( int i = 0; i < len; i++ )
{ cin >> *(marks+i);
}
for( int i = 0; i < len; i++ )
{
sum += *(marks+i);
}
cout << "sum is " << sum << endl; return 0; }
Comments
Post a Comment