Lecture-24 (21-11-23)
Lecture-24 (21-11-23)
MA144:
Computer Programming
Lecture-24
Dynamic Arrays
Redefine dataTypes using typedef
• We can use typedef to define alias for any type name of definition.
Examples
• typedef int iece;
Now we can define a variable type int as iece a,b;
int a,b; and iece a,b; are equivalent.
return a;
}
1-D Dynamic Arrays
A dynamic array is an array whose size is not specified
when you write the program, but is determined while
the program is running.
delete [] p;
return 0;
}
2-D Dynamic Arrays
Pointer to a pointer variable
• Declaration
int **p;
p=new int *[m];
It is an array of m pointers.
Each p[i] can name a dynamic array of n ints as
for(i=0;i<m;i++)
p[i]=new int [n];
It creates a dynamic array p of size m-by-n
• Eliminate the 2-D dynamic array as
for(i=0;i<m;i++)
delete [] p[i];
delete [] p;
Note that elimination is reverse to declaration process
#include<iostream>
using namespace std;
int main()
{
int m, n,i,j,**p;
cout<<"\n enter no. of rows: ";
cin>>m;
cout<<"\ enter no. of columns: ";
cin>>n;
//declaring 2-D dynamic array
p=new int *[m];
for(i=0;i<m;i++)
p[i]=new int [n];
//reading array elements
cout<<"\n enter array:\n ";
for(i=0;i<m;i++)
{ cout<<"enter row "<<i<<" with "
<<n<<" elements: ";
for(j=0;j<n;j++)
cin>>p[i][j];
cout<<endl;
}
//accessing array elements
for(i=0;i<m;i++)
for(j=0;j<n;j++)
p[i][j]+=1;
//printing array
cout<<"\n modified array:\n ";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<p[i][j]<<" ";
cout<<endl;
}
//eliminating dynamic arrays
for(i=0;i<m;i++)
delete [] p[i];
delete [] p;
return 0;
}