Friday, August 31, 2018

Dynamic Array


Dynamic Array

In dynamic array array the memory to Array will be allocated at run-time.
Here we will use pointers to do that.

Down below is the simple program to Delclare and Initialize a Dynamic Array.

#include<iostream>
using namespace std;
int main()
{
int *arr,i; //Line 1
arr=new int[5]; //Line 2
cout<<"\n Enter the elements : ";
for(i=0;i<5;i++)
{
cin>>*(arr+i); //Line3
}
cout<<"\n Array is : ";
for(i=0;i<5;i++)
{
cout<<" "<<*(arr+i);
}
delete arr;
return 0;
}

Explaintion :-
  • Line 1- Pointer of integer type is declared.
  • Line 2- Memory for storing 5 integer is allocated.
arr will contain the address of the first element in the array.
i.e, arr=&arr[0]
  • Line 3- The array is being initialised like this:-
*arr=arr[0]
*(arr+1)=arr[1] = With each increment in pointer the the next address is pointed.
.
.
*(arr+4)=arr[5]

This is how Dynamic array works.

For any doubts Comment Below.


No comments:

Post a Comment