C - Filling a structure

Introduction

You can assign values to a structure variable when it's created.

You first define the structure type and declare a structure variable with its member values preset.

Ensure that the preset values match the order and type of members defined in the structure.

Demo

#include <stdio.h> 

int main() /* w  ww  . j  a v  a 2s .  c  o m*/
{ 
   struct president 
   { 
       char name[40]; 
       int year; 
   }; 
   struct president first = { 
       "George Washington", 
       1789 
   }; 

   printf("The first president was %s\n",first.name); 
   printf("He was inaugurated in %d\n",first.year); 

   return(0); 
}

Result

You can also declare a structure and initialize it in one statement:

struct president 
{ 
   char name[40]; 
   int year; 
} first = { 
   "George Washington", 
   1789 
}; 

Related Topic