One Two and Multi Dimentional array initalization in C++

Array in C++, One Dimensional, Two Dimentional, Multi Dimensional Array


Arrays in C++:   

 An array is a sequence of data in memory where in all the data are of the same type and are placed in physically adjacent location.
(1)    One dimensional.
(2)    Two dimensional
(3)    Multi dimensional

Array Declaration:
(1)    Type of the array (i.e. integer , float , char type etc)
(2)    Name of the array
(3)    Number of subscript in the array ( one-D , two-D etc)
(4)    Total number of memory location to be allocated

Syntax :  storage_class data_type array_name[const]

      int  marks[10], a[12][10];
      static char page[8];

      int value  [0];// invalid       float num [-10]// invalid
     char s[$];  //invalid

Array Initialization:

(1)    Compile time initialization

 int marks [5] = { 1,2,3,4};
Marks[0] = 1    Marks[1] = 2    Marks[2] = 3    Marks[3] = 4    Marks[4] = 0
 
char name [4] = { ‘R’ , ‘E’ , ‘N’ , ‘U’};

name[0] = R    name[1] = E    name[2] = N    name[3] = U

int x[2][2] = {1,2,3,4};

x[0][0] = 1    x[0][1] = 2    x[1][0] = 3    x[1][1] = 4   

int A[3][3] = {
                      {1, 2, 3},
           {4, 5, 6},
           {7, 8, 9}
        };
 

(2)    Run time initialization

#define max 10
void main()
{
  int marks[max];
  for ( i= 0 ; i< max-1 ; i++)
  {
    cin>>marks[i];
  }
}


#define N 4
#define M 4
void main()
{
  int marks[N][M];
  for ( i= 0 ; i<N-1 ; i++)
 {
    for ( j= 0 ; j<M-1 ; j++)
     cin>>marks[ i ][ j ];
  }
}

Character Type array :

 When initializing a character array in ANSI C, the compiler will allow us to declare the array size as the exact length of the string constant
                       
                       char  name[3]=”red”;   // valid in ANSI C
But in C++ the size should be one larger than the number of characters in the string.
                        char  name[4]=”red”;   //o k for C++

Labels: