Tuesday 12 February 2013

Initialisation of Arrays in C Programming Language


An array can be initialised when declared by specifying the values of some or all of its elements. This initialisation at the time of declaration is possible only outside a function unless it is declared static. Static declarations will be discussed in a later session, and hence for present purposes we shall work on the assumption that direct initialisation is done outside the function. Direct initialisation is possible in many ways :

char str1[7]={'A','B','O','D','U','S','\0'};
char str2[7]={"ABODUS"};

In the first case, individual elements have been moved into the array and hence it is essential that the string terminator be specified explicitly. In the second case, the string terminator gets attached automatically since a string has been assigned.

int ages[]={12,23,34,45,56};

In case of integers and floats, individual values have to be moved into the elements. In the above declaration, the dimension has not been specified for reasons of flexibility. The compiler will automatically calculate the dimension based on the initialisation.

0 comments:

Post a Comment

Powered by Blogger.