Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Allocating  a  Fixed - Dimensional  Array

The  new  operator,  when  used  with  the  name  of  a  pointer  to  a  datatype  allocates memory  for  the  item  and  assigns  the  address  of  that  memory  to  the  pointer.

This  example  shows  how  you  can  use  new  and  delete  to  acquire  and  dispose  of memory  for  an  array.



                       # include  <iostream.h>
                       int  main ( )
                       {
                                   int  *q  = new  int [ 3 ] ;
                                   q [ 0 ] = 6 ;
                                   q [ 1 ] = 7 ;
                                   q [ 2 ] = 8 ;
                                   cout  <<  q [ 0 ]  <<  q [ 1 ]  <<  q [ 2 ] ;
                                   delete [ ] q ;
                                   return  0 ;
                        }



Allocating  Dynamic  Arrays

You  can  supply  a  variable  dimension,  and  the  new  operator  allocates  the  correct  amount of  memory.

This  example  shows  how  you  can  use  new  and  delete  to  acquire  and  dispose  of memory  for  a  variable  dimension  array.


                                   # include  <iostream.h>
                                   int  main ( )
                                   {
                                               cout  << " Enter  the  array  size " ;
                                               int  size ;
                                               cin  >>  size ;
                                               int  *q  = new  int [ size ] ;
                                               for ( int i = 0 ; i < size ; i++ )  //  load  the  array  with  1, 2 ..... size
                                               q [ i ] = i + 1 ;
                                               for ( int i = 0 ; i < size ; i++ )   //  displays  elements  in  the  array
                                               cout  <<  q [ i ] ;
                                               delete [ ] q ;
                                               return  0 ;
                                    }



When  running  this  exercise,  you  first  type  in  the  size  of  the  array.  The  new  operator uses  that  value  to  establish  the  size  of  the  memory  to  be  allocated. The  program  builds the  array  by  using  the  new  operator,  fills  it  with  values ( 1, 2 .......   size ), displays  each of the  elements  in  the  array,  and  deletes  the  array  by  using  the  delete operator.