Structure in C Programming: How to Create and Use Programs
This article is a complete guide to understanding the meaning of C structure and by the end of this article you will understand how to use and when to use a structure in your C program.
A struct or structure in C programming is a collection of logically related variables of different data types. The structure variables are stored in one place to solve a single purpose means they all refer to the same entity.
For example, declare an employee structure that contains member variables like id, salary, name, and age, providing information about an employee or its employee data. There are various real-life examples where we can use structures to store library book data and hospital patient records.
There are various data types to store different variables and arrays to store multiple similar data types. The structure is the only user-defined data type that is used to store different variable types in a single container.
Explore C Programming Courses
In this article, we will study one of the important concepts of C programming. We will go through the meaning of C structure and implement it using several C programs. The main focus of this article is to make you comfortable with using the C structure.
What is a Structure?
A structure is a container to store multiple types of variables. The variables stored in a structure are called member variables. Member variables are related to each other, and they are combined to provide complete information about an object.
Why do we Use Structure? This question must be in your mind that we have C data types to declare variables. Why do we use a new function in C?
Understand the answer through this example. A company wants to record its employee information, including name, id, and salary. There are 100 employees. You will declare variables for each entity and 100 employees. Which means a total of 100 x 3 = 300 variables.
This is an unfeasible, time-consuming, and not smart way of coding. Your program becomes unreadable and consumes lots of memory. To work in these similar situations, we use a C structure that can define all these entities in a single name.
You can read C programming books on Structures additionally.
We will create a program using the C structure for this situation in the coming sections of the article.
Key Points of C Structure
- The structure is declared using the βstructβ keyword.
- Structure allocates contiguous memory to all its member variables.
- You can only declare member variables in a structure.
- You cannot initialize the member variables during their declaration.
- To access the member variables, use the dot operator.
- Structure member variables are initialized in the same order as their declaration.
Best-suited C / C++ courses for you
Learn C / C++ with these high-rated online courses
How to Create a Structure in C Programming
A structure is created by using the struct keyword and declaring all member variables in its body, with opening and closing braces. The opening braces after a structure declaration define the starting of its body. The closing braces indicate the end of a structure body.
A structure definition consists of two parts:
- Structure declaration
- Structure Body
Syntax of Structure:
struct stuct_name //structure declaration{ //Member variables data_type member1_name; data_type member2_name; : :};
For Example:
struct student{ char name [50]; int id; int class;};
A structure variable is used to initialize and access all the member variables. There are two ways to declare a structure variable.
- First way to declare a structure variable
struct employee{ int id; char name[70];}e;
Here, βeβ is the structure variable, declared after the structure bodyβs closing braces.
- Second way to declare a structure variable
struct employee{ int id; char name[70];};
int main(){ struct employee e;}
Here, the structure variable βeβ is declared in the main function after the declaration of the structure.
You can use any of the ways to declare the structure variable.
Programs to Use Structure in C
Implementing a structured program to print data of a student with individual initialization of member variables.
#include <stdio.h>#include<string.h>//Declaring structurestruct Student{ char name[50]; int id; int class;};
int main(){ //declaring structure variable struct Student s;
printf("Data of first student\n" );//Initializing the member variables individually strcpy(s.name, "Rahul"); s.id = 101; s.class = 1;//Accessing the member variables printf("Student Name: %s", s.name); printf("\nStudent Id: %d", s.id); printf("\nStudent Class: %d", s.class); printf("\nData of second student\n" ); strcpy(s.name, "Raj"); s.id = 102; s.class = 2; printf("Student Name: %s", s.name); printf("\nStudent Id: %d", s.id); printf("\nStudent Class: %d", s.class); printf("\nData of second student\n" ); strcpy(s.name, "Ravan"); s.id = 103; s.class = 3; printf("Student Name: %s", s.name); printf("\nStudent Id: %d", s.id); printf("\nStudent Age: %d", s.class);
return 0;}
Output:
***********Data of first student*********** Student Name: Rahul Student Id: 101 Student Class: 1 ********Data of second student*********** Student Name: Raj Student Id: 102 Student Class: 2 *********Data of second student********* Student Name: Ravan Student Id: 103 Student Age: 3
Note: In the above program, we individually initialize each member variable using the dot product of the structure variable and the member variables. Using a single function, we can keep a record of the number of students.
Implementing a structured program to print employee data with initializing member variables simultaneously.
#include <stdio.h>#include<string.h>
struct data { int num; char letter; char name[30];};
int main() { // Create a structure variable and assign values to it struct data d = {10, 'A', "Structure"};
// Print values printf("The values of data are: %d %c %s", d.num, d.letter, d.name);
return 0;}
Output:
The values of data are: 10 A Structure
How to Initialize Structure Member Variables
Structure member variables are not similar to the other data type variables in C. They have certain characteristics for their initialization. The member variables are initialized in the same sequential order in which they are declared.
To initialize the structure member variable, you need to declare a structure variable. There can be any number of structure variables, each variable defines a different data set of the structure.
For example:
struct student{int x, y;};int main(){//Declaring structure variable s1 and s2 struct student s1; struct student s2; return 0;}
You cannot initialize the structure member variables at the time of their declaration, this will generate a compiler error. The reason is the compiler does not create any memory during variable declaration. While the second reason is, that structure member variables are initialized in curly braces {} using the structure name.
For example:
#include <stdio.h>struct Person{ int age = 20; char gender = "M"}
OUTPUTerror: expected β:β, β,β, β;β, β}β or β__attribute__β before β=β token 12 | int age = 20; | ^
The correct way to initialize the structure member variables is as follows:
#include <stdio.h>struct Person{ int x; int y;};int main(){//Initializing structure member variables x and y using structure variable struct Person p = {10, 20}; return 0;}
Nested Structure in C Programming
The structure which contains another structure is called a nested structure. The outer structure we can use as a data type inside the other structure. Consider an example to understand the logic of the nested structure.
Example to Create a nested structure
struct address_data{ int street_number; char street_name; int house_number;}struct student_data{ char name[50]; int id; struct address_data address;}
#include <stdio.h>struct student_address{ int street; char *state; char *city;};
struct student_data{ int id; char *name; struct student_address address;};int main(){ struct student_data d; d.id = 1002; d.name = "Shivam"; d.address.street = 101; d.address.state = "Rajasthan"; d.address.city = "Jaipur"; printf("**********Student Data*********** "); printf("\nStudent id: %d",d.id); printf("\nStudent name: %s",d.name); printf("\nStudent street: %d", d.address.street); printf("\nStudent state: %s",d.address.state); printf("\nStudent city: %s",d.address.city);
return 0;}
Output
**********Student Data*********** Student id: 1002 Student name: Shivam Student street: 101 Student state: Rajasthan Student city: Jaipur
How to Access the Structure Member Variables
Use the dot (.) operator to access the structure member variables. After initializing the member variables, access them in the main function using the dot operator with structure variables.
For example:
#include <stdio.h>struct Person{ int age; char name[40];};int main(){ //initializing the structure member variables with structure variable p struct Person p = {30, "Sonal"}; printf("The name of the person is %s\n", p.name); //accessing the member variables printf("Age of the person is %d", p.age); return 0;}
OUTPUT
The name of the person is Sonal
Age of the person is 30
NOTE: You can access the structure member variables by declaring the structure variable. In the above code, βpβ is the structure variable, and we can use it for the dot operator with the member variable.
Designed Initialization of C Structure
You can initialize the structure member variables in the order they are declared. But, in case, you want to initialize the member variables in random order you can use the designed initialization property of C.
Designed Initialization allows structure member variables initialization in any order. So, to implement this property, you have to use the structure variable with the dot operator.
Program to implement the designed implementation
#include <stdio.h>struct variable{ int x, y, z;};
int main(){ struct variable v= {.y = 20, .x = 10, .z = 30}; //Designed Initialization //Accessing member variables printf("The value of x is: %d\n", v.x); printf("The value of y is: %d\n", v.y); printf("the value of z is: %d", v.z); return 0;}
OUTPUT
The value of x is: 10
The value of y is: 20
The value of z is: 30
Program to Create C Structure to Print Different Employee Information
#include<stdio.h> #include <string.h> struct employee { int id; char name[50]; int salary; };
int main( ) { //Initializing member variables, e1 & e2 are structure variables struct employee e1 = {201, "Abhishek Singh", 50000}; struct employee e2 = {202, "Maya Sharma", 80000}; //printing first employee information printf("Information of employees\n"); printf( "Employee id : %d\n", e1.id); printf( "Employee name : %s\n", e1.name); printf( "Employee salary : %d\n", e1.salary);
printf("*******************"); //printing second employee information printf( "\nEmployee id : %d\n", e2.id); printf( "Employee name : %s\n", e2.name); printf( "Employee salary : %d\n", e2.salary); return 0; }
OUTPUT
Information of employees
Employee id : 201
Employee name : Abhishek Singh
Employee salary : 50000
*******************
Employee id : 202
Employee name : Maya Sharma
Employee salary : 80000
The structure in C is a convenient tool to group different data types in one place, and the compiler allocates contiguous memory to all logically related variables. There are some disadvantages of the C structure.
Disadvantages of Structure in C Programming
- The C compiler does not allow the declaration of struct data types as built-in data types.
- You cannot use different operators like +, *, and more on the structure member variables. If you try to use the operators, the compiler will generate errors.
Conclusion
We have reached the end of this article. We learned the concept of structure with its use in different C programs. Using the designated initialization; you can initialize the structure member variables in random order.
Along with the importance of the C structure, it has a limitation: it does not allow data hiding, you cannot use static memes inside the structure, and you cannot define a function inside a C structure. Structure in C programming does not support access modifiers and constructor declaration inside its body.
Contributed By: Sonal Meenu Singh
FAQs
What is structure give an example using program.
The structure is a user-defined data type that stores several types of variables under a single name. The declared variables in a structure are its member variables and are logically interrelated. The program to use a structure is as follows: #include struct number { int a; int b; }; int main() { struct number n = {10, 20}; printf("he value of a and b are: %d %d", n.a, n.b); return 0; }
What is the syntax of structure in C?
The syntax of C structure is simple and easy to implement. struct structure_name { data_type member_variable1; data_type member_variable2; data_type member_variable3; : };
How is a structure variable initialized?
The variables declared in the structure body are called member variables. They are not initialized at their declaration time. Member variables are initialized using the structure variable in the main function. There are three ways to initialize the member variables. First: use curly braces to initialize all variables at one place. Second: use the dot operator to individually initialize each member variable. Third: use designed initialization.
What is meant by a structure variable?
A structure variable is a variable declared outside the C structure and it is used to initialize and access the member variables.
What are the benefits and advantages of using structures in C?
The structure is useful in a situation when you want to store several logically related variables in one place. It allocates contiguous memory to all its variables.
What are the disadvantages of structures in C?
1. Code complexity increases. 2. Slower the processing. 3. You cannot use mathematical operators on struct member variables.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio