Array Initialization in C Language

Array Initialization in C – Arrays can be initialized at the time of declaration. The initial values must appear in the order in which they will be assigned to the individual array elements, enclosed within the braces and separated by commas. In the following section, we see how this can be done.

Initialization of Array Elements in the Declaration

The values are assigned to individual array elements enclosed within the braces and separated by comma. Syntax of array initialization is as follows:

data type array-name [ size ] = {val 1, val 2, .val n};

 

val 1 is the value for the first array element, val 2 is the value for the second element, and val n is the value for the n array element. Note that when you are initializing the values at the time of declaration, then there is no need to specify the size.

Let us see some of the examples given below:

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

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

int vector[5] = {12,-2,33,21,13};

float temperature[10] ={ 31.2, 22.3, 41.4, 33.2, 23.3, 32.3, 41.1, 10.8, 11.3, 42.3};

double width[ ] = { 17.33333456, -1.212121213, 222.191345 };

int height[ 10 ] = { 60, 70, 68, 72, 68 };

 

Character Array Initialization in C

The array of characters is implemented as strings in C. Strings are handled differently as far as initialization is concerned. A special character called null character ‘ \0 ’, implicitly suffixes every string. When the external or static string character array is assigned a string constant, the size specification is usually omitted and is automatically assigned; it will include the ‘\0’character, added at end.

For example, consider the following two assignment statements:

 

char thing [ 3 ] = “TIN”;
char thing [ ] = “TIN”;

 

 

In the above two statements the assignments are done differently. The first statement is not a string but simply an array storing three characters ‘T’, ‘I’ and ‘N’ and is same as writing:

char thing [ 3 ] = {‘T’, ‘I’, ‘N’};

 

whereas, the second one is a four character string TIN\0. The change in the first assignment, as given below, can make it a string.

char thing [ 4 ] = “TIN”;

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
?>