• Articles
  • Tutorials
  • Interview Questions
  • Webinars

Structures and Unions in C

What are Structures in C?

Structure stores the different types of elements i.e heterogeneous elements. The struct keyword is used to define structure.
Syntax

struct structure_name
{
data_type member1;
 
data_type memeberN;
};

Watch this C Programming and Data Structure Video by Intellipaat:

Youtube subscribe

Declaring structure variable

You can declare structure variable in two ways:-

1. By struct keyword within main() function

2. By declaring variable at the time of defining structure.

Example

#include <stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[60];
}s1;  //declaring s1 variable for structure
void main( )
{
//store first employee information
s1.rollno=1;
strcpy(s1.name, “intellipaat”);//copying string into char array
//printing first employee information
printf( "Rollno : %dn", s1.rollno);
printf( "Name : %sn", s1.name);
}

Output
Rollno : 1
Name : intellipaat

Certification in Full Stack Web Development

What are Unions in C?

Union also stores the different types of elements i.e heterogeneous elements. The union keyword is used to define structure. Union takes the memory of largest member only so occupies less memory than structures.
Syntax

union union_name
{
data_type member1;
 
data_type memeberN;
};

Example

#include <stdio.h>
#include <string.h>
union student
{
int rollno;
char name[60];
}s1;  //declaring s1 variable for union
void main( )
{
//store first employee information
s1.rollno=1;
strcpy(s1.name, “intellipaat”);//copying string into char array
//printing first employee information
printf( "Rollno : %dn", s1.rollno);
printf( "Name : %sn", s1.name);
}

Output
Rollno : 3546656
Name : intellipaat
Rollno takes garbage value because name has large memory size. So only name will have actual value.

If you want to learn C programming, refer to our C programs blog!

Get 100% Hike!

Master Most in Demand Skills Now !

Course Schedule

Name Date Details
Python Course 20 Jul 2024(Sat-Sun) Weekend Batch
View Details
Python Course 27 Jul 2024(Sat-Sun) Weekend Batch
View Details
Python Course 03 Aug 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Senior Consultant Analytics & Data Science

Presenting Sahil Mattoo, a Senior Consultant Analytics & Data Science at Eli Lilly and Company is an accomplished professional with 14 years of experience across data science, analytics, and technical leadership domains, demonstrates a remarkable ability to drive business insights. Sahil holds a Post Graduate Program in Business Analytics and Business Intelligence from Great Lakes Institute of Management.