C initializing array of structure



Initializing Array of Structure in C Programming

  1. Array elements are stored in consecutive memory Location.
  2. Like Array , Array of Structure can be initialized at compile time.

Way1 : Initializing After Declaring Structure Array :

struct Book
{
     char bname[20];
     int pages;
     char author[20];
     float price; 
}b1[3] = {
           {"Let us C",700,"YPK",300.00},
           {"Wings of Fire",500,"APJ Abdul Kalam",350.00},
           {"Complete C",1200,"Herbt Schildt",450.00}
         };

Explanation :

As soon as after declaration of structure we initialize structure with the pre-defined values. For each structure variable we specify set of values in curly braces. Suppose we have 3 Array Elements then we have to initialize each array element individually and all individual sets are combined to form single set.

{"Let us C",700,"YPK",300.00}

Above set of values are used to initialize first element of the array. Similarly –

{"Wings of Fire",500,"APJ Abdul Kalam",350.00}

is used to initialize second element of the array.

Way 2 : Initializing in Main

struct Book
    {
     char bname[20];
     int pages;
     char author[20];
     float price; 
};

void main()
{
struct Book b1[3] = {
        {"Let us C",700,"YPK",300.00},
        {"Wings of Fire",500,"Abdul Kalam",350.00},
        {"Complete C",1200,"Herbt Schildt",450.00}
    };
}

Some Observations and Important Points :

Tip #1 : All Structure Members need not be initialized

#include<stdio.h>
struct Book
{
     char bname[20];
     int pages;
     char author[20];
     float price; 
}b1[3] = {
           {"Book1",700,"YPK"},
           {"Book2",500,"AAK",350.00},
           {"Book3",120,"HST",450.00}
         };

void main()
{
    
printf("\nBook Name    : %s",b1[0].bname);
printf("\nBook Pages   : %d",b1[0].pages);
printf("\nBook Author  : %s",b1[0].author);
printf("\nBook Price   : %f",b1[0].price);

}

Output :

Book Name    : Book1
Book Pages   : 700
Book Author  : YPK
Book Price   : 0.000000

Explanation :

In this example , While initializing first element of the array we have not specified the price of book 1.It is not mandatory to provide initialization for all the values. Suppose we have 5 structure elements and we provide initial values for first two element then we cannot provide initial values to remaining elements.

{"Book1",700,,90.00}

above initialization is illegal and can cause compile time error.

Tip #2 : Default Initial Value

struct Book
{
     char bname[20];
     int pages;
     char author[20];
     float price; 
}b1[3] = {
           {},
           {"Book2",500,"AAK",350.00},
           {"Book3",120,"HST",450.00}
         };

Output :

Book Name    : 
Book Pages   : 0
Book Author  : 
Book Price   : 0.000000

It is clear from above output , Default values for different data types.

Data TypeDefault Initialization Value
Integer0
Float0.0000
CharacterBlank