C Language | Arrays | Initializing Arrays

Arrays can initialize their elements when they are declared.

Initializing Array Variables

Provide an initializer list in braces.

type variable[element-count] = { value1, value2, value3, ... };

The list cannot contain more values than the array has elements. If it contains fewer values, the remaining elements are initialized to zero.

int iArray[4] = { 10 , 100 , 1000 , 10000 };

Code 1

#include <stdio.h>

int main() {
 int iArray[4] = { 10 , 100 , 1000 , 10000 } , iCount;
 for(iCount = 0 ; iCount < 4 ; iCount++)
   printf("iArray[%d] = %d\n" , iCount , iArray[iCount]);
 return 0;
}

A character array can be initialized one character at a time. Remember the terminating null character.

Code 2

#include <stdio.h>

int main() {
 char chStr[6] = { 'K' , 'i' , 't' , 't' , 'y' , 0 };
 printf("%s\n" , chStr);
 return 0;
}

A string literal adds the terminating null character automatically.

Code 3

#include <stdio.h>

int main() {
 char chStr[6] = "Kitty";
 printf("%s\n" , chStr);
 return 0;
}

Initializing Multidimensional Arrays

Use nested initializer lists for multidimensional arrays.

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

Missing values are initialized to zero.

Code 4

#include <stdio.h>

int main() {
 int row , column;
 int iArray[3][3] = {
   { 2 , 4 },
   { 8 , 16 , 32 }
 };

 for(row = 0 ; row < 3 ; row++)
   for(column = 0 ; column < 3 ; column++)
     printf("iArray[%d][%d] = %d\n" , row , column , iArray[row][column]);
 return 0;
}

A flat list also fills a multidimensional array in order.

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

Arrays of strings are represented as multidimensional character arrays.

Code 5

#include <stdio.h>

int main() {
 char chStr[3][8] = { "Kitty" , "Kitten" , "Feline" };
 printf("%s : %s : %s\n" , chStr[0] , chStr[1] , chStr[2]);
 return 0;
}

Omitting the Element Count

When an initializer determines the required size, omit the element count but keep the brackets.

int iArray[] = { 1 , 2 , 3 };
char chStr[] = "Kitty on your lap";

This avoids manually calculating the storage required for a string and its terminating null character.