Friday, 24 January 2014

INITIALIZATION OF ARRAY IN C++

 




Garbage value will be initialized if we use this format.
int  arr[10];

In this case all the elements of the array will be initialized to zero because of the keyword static.
static int arr[10];

This code will initialize the all elements of the array to zero.
int arr[10]={0};

This  will initialize the all elements of the array to zero.
int arr[10]={};

This will initialize the first two elements of the array as initialized and remaining all elements will be initialized as zero.
int arr[10]={1,2}

This kind of initialization is not possible in c program. You have to use either the for loop or memcpy for initialization.
int arr1[10]={1,2,3,4,5};
// int arr2[10]=arr1;  This kind of initialization is not possible in c program

The char array can be initialized using the doble quotes. But it is not possible in the case of float and int.
char c[10]=”hello”;
// int i[10]=”12345”; Not possible for int,float

The array can be explicitly initialized using the above format. In case of int the remaining array will be initialized to zero. In case of char strlen returns zero if the first element of the array was not initialized.
int array[10]={[2]=2,[5]=1};
char c[10]={[2]=’a’,[3]=’d’};//strlen(c) is zero.

The above will initialize the 1st element of array to empty space. In similar fashion if you leave two spaces then the first two index will be initialized to empty space.
char c[10]=” “;

The two array cannot be intialized without mentioning the size at both the dimensons. But you can intialize by without specifying the 1st dimenson.

int arr[]={12,5,8} // This is valid in c and c++
int arr[][]={{1,3},{2,5}}; // Not valid in c and c++
int arr[][10]={{1,3},{2,5}}; //  valid in c and c++




IMG SRC: http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.html