How to create struct - C Structure

C examples for Structure:Structure Definition

Introduction

Build the structure definition using the struct keyword followed by braces.

Include individual variables as members.

struct math { 
   int x; 
   int y; 
   int result; 
}; 

Create an instance of the structure.

struct math aProblem; 

To initialize a structure instance.

struct math aProblem = { 0, 0, 0}; 

Or

//assign values to members 
aProblem.x = 10; 
aProblem.y = 10; 
aProblem.result = 20; 

//print the contents of aProblem 

printf("\n%d plus %d", aProblem.x, aProblem.y); 

printf(" equals %d\n", aProblem.result); 

Demo Code

#include <stdio.h> 
#include <string.h> 

struct employee { 
   char fname[10]; 
   char lname[10]; 
   int id; //  www . j  a v a2  s  . c  om
   float salary; 
}; 
int main()
{ 
   //create instance of employee structure 
   struct employee emp1; 
   //assign values to members 
   strcpy(emp1.fname, "Edith"); 
   strcpy(emp1.lname, "Grand"); 
   emp1.id = 123; 
   emp1.salary = 12345.00; 

   //print member contents 
   printf("\nFirst Name: %s\n", emp1.fname); 
   printf("Last Name: %s\n", emp1.lname); 
   printf("Employee ID: %d\n", emp1.id);  
   printf("Salary: $%.2f\n", emp1.salary); 
}

Result


Related Tutorials