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

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree