C initializing structure



We have already learnt the topic for declaring structure variable in C. In this tutorial we will be learning how structure is initialized in c programming.

C Structure Initialization

  1. When we declare a structure, memory is not allocated for un-initialized variable.
  2. Let us discuss very familiar example of structure student , we can initialize structure variable in different ways –

Way 1 : Declare and Initialize

struct student
{
   char name[20];
   int roll;
   float marks;
}std1 = { "Pritesh",67,78.3 };

In the above code snippet, we have seen that structure is declared and as soon as after declaration we have initialized the structure variable.

std1 = { "Pritesh",67,78.3 }

This is the code for initializing structure variable in C programming

Way 2 : Declaring and Initializing Multiple Variables

struct student
{
   char name[20];
   int roll;
   float marks;
}

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

Way 3 : Initializing Single member

struct student
{
   int mark1;
   int mark2;
   int mark3;
} sub1={67};

Though there are three members of structure,only one is initialized , Then remaining two members are initialized with Zero. If there are variables of other data type then their initial values will be –

Data Type Default value if not initialized
integer 0
float 0.00
char NULL

Way 4 : Initializing inside main

struct student
{
    int mark1;
    int mark2;
    int mark3;
};

void main()
{
struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};

When we declare a structure then memory won’t be allocated for the structure. i.e only writing below declaration statement will never allocate memory

struct student
{
    int mark1;
    int mark2;
    int mark3;
};

We need to initialize structure variable to allocate some memory to the structure.

struct student s1 = {89,54,65};