Structures in C – Makes Coder Life Easy

Get Certified in C Programming for Free and Take Your Skills to the Next Level

So far, we discussed the various user-defined data types available in C such as union, enumeration, and typedef. But we are yet to discuss one of the most important user-defined data type called structures in C.

C Structures are the optimal way to represent data as a whole. We use structures to overcome the drawback of arrays.

We already know that arrays in C are bound to store variables that are of similar data types. Creating a structure gives the programmer the provision to declare multiple variables of different data types treated as a single entity.

In this tutorial, we will discuss:

  • Significance of Structures in C
  • Create a Structure in C
  • Meaning of Array of Structures
  • Simplify the syntax of structure using typedef
  • Nested Structures in C
  • Pass structures to a function
  • Access Structures using pointers
  • Difference between Structure in C and C++

1. What are Structures in C?

In layman language, a structure is nothing but a cluster of variables that may be of different data types under the name name.

In programming terminology, a structure is a composite data type (derived from primitive data types such as int and float) that we use in order to define a collection of similar or different data types under one same name in a particular block of computer memory.

Structure in C Programming

2. Significance of Structures in C

Now that we understood the primary purpose of structures, let us acknowledge its significance by considering a very simple problem at hand.

Suppose you want to take the input of a particular date and display it. It would probably be a lot easier if we treat the records of the structure (day, month and year) as a single unit by logically relating them with each other.

Here is a program in C that illustrates how to solve the above problem:

#include <stdio.h>
struct date
{
unsigned int day, month, year;
};
int main()
{

struct date d = {12, 11, 2020}; // Here d is an object of the structure time

printf("Welcome to DataFlair tutorials!\n\n");

printf("The Date is %d / %d / %d\n", d.day, d.month, d.year);
return 0; 
}

Code- 

Example of Structures in C

Output-

Output of Structures in C

Now, let us consider another scenario where you want to store an employee’s records such as his name, age, and salary under a single unit. In this case, all the 3 records are of different types but can easily be clubbed into one with the help of structures.

Unveil the Difference between Structures and Unions in C

Here is a program in C that illustrates how to solve the above problem:

#include <stdio.h>
struct employee
{
char name[30];
int age;
float salary;
};
int main()
{

struct employee e = {"Rachel", 29, 60000}; // Here e is an object of the structure employee

printf("Welcome to DataFlair tutorials!\n\n");

printf("The name is: %s\n",e.name);
printf("The age is: %d\n",e.age);
printf("The salary is: %0.2f\n",e.salary);
return 0; 
}

Code- 

Structures in C with Example

Output-

Structures in C with results

3. How to Create Structures in C?

A structure is created outside the main function, preferably before the main function. In order to access the data members of the structure, variable(s) are created either inside or outside the main function depending upon the choice of the programmer.

The struct keyword is used to indicate the definition of a structure.

Syntax of the body of the Structure-

struct structure_name
{
data_type data_member1;
data_type data_member2;
data_type data_member3;
.

data_type data_membern;
};

For instance,

struct book
{
char book_name[30];
char author[30];
int book_id;
float price;
};

4. How to Create Structure Variables?

As stated above, we can’t directly access the data members of a structure. We need to create at least one variable to access the structure. The variable is responsible for reserving a particular block of memory for the structure according to its size.

There are 2 ways to create a variable to access data members in a structure:

1. Inside the main function:

struct book
{
char book_name[30];
char author[30];
int book_id;
float price;
};
int main()
{
struct book b; // Here b is a variable of structure book
}

2. Outside the main function:

struct book
{
char book_name[30];
char author[30];
int book_id;
float price;
} b; // Here b is a variable of structure book.

There is no difference in the way memory is allocated or how the data members are accessed through the variables in both cases.

5. How to access Data Members in Structures in C

There are basically two ways in order to access the data members in a structure through variable(s):

  • With the help of the member operator/ dot symbol (.)
  • With the help of structure pointer operator (->)

Suppose you want to access the data member book_id from the structure book, this is how you would do it using the member operator.

b.book_id;

For simplicity sake, we would prefer to use the dot operator in most of the cases. We will discuss the structure pointer operator in detail in the later section as it involves the use of pointers.

Let us merge together all the concepts involved in creating a structure by implementing a program in C to take input and display the details of a book using structures:

#include<stdio.h>
struct book
{
char book_name[30];
char author[30];
int book_id;
float price;
};

int main()
{

struct book b; // Here b is a variable of structure book

printf("Welcome to DataFlair tutorials!\n\n");

printf("Enter the book name: ");
fgets(b.book_name, 30, stdin);
printf("Enter the author name: ");
fgets(b.author, 30, stdin);
printf("Enter the book ID: ");
scanf("%d",&b.book_id);
printf("Enter the book price: ");
scanf("%f",&b.price);

printf("\nThe details of the book are:\n\n");
printf("The book name is: ");
puts(b.book_name);
printf("The author name is: ");
puts(b.author);
printf("The book ID is: %d\n\n",b.book_id);
printf("The book price is: %0.2f\n",b.price);
return 0;
}

Code – 

Creating Structures in C

Output-

Structures in C

Key takeaway: It is important to note that in structures, only data members can be defined, they can’t be initialized a specific value inside its definition. Also, functions cannot be declared within a structure.

Here is a code in C that illustrates what happens when we try to initialize data members and declare member functions:

#include<stdio.h>
struct DataFlair
{
int number = 5; // Compilation error
char character = 'D'; // Compilation error
float fraction = 33.33; // Compilation error
};

int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

struct DataFlair d;
printf("The number is: %d\n",d.number);
printf("The character is: %c\n",d.character);
printf("The fraction is: %f\n",d.fraction);
return 0;
}

Code-

Initialize and declare member functions in C

6. The array of Structures in C

Before discussing this topic, it is important to have a crystal clear understanding of arrays in C.

We already know that arrays and structures allow the grouping of elements under one roof, but if implemented together, arrays and structures can extend its functionality to another level.

In order to understand the array of structures, let us consider the base problem at hand and make slight modifications. Suppose you want to take the input and display all the records of 3 books, you can do it in two ways:

  • Create 5 variables to access the data members of the structure: b1, b2, and b3.
  • Create an array of structures b[3].

What sounds more convenient and easy to implement? Obviously the 2nd method.
This is where the array of structures comes into play.

Here is a code in C that illustrates the implementation of the array of structures with reference to the above-stated problem:

#include<stdio.h>
struct book
{
char book_name[30];
char author[30];
int book_id;
float price;
};

int main()
{

struct book b[3]; // Here b is a variable of structure book
int i;
printf("Welcome to DataFlair tutorials!\n\n");

printf("Enter the record of 5 books:\n");
for(i = 0; i < 3; i ++)
{
printf("Enter the book name: ");
scanf("%s",b[i].book_name);
fgets(b[i].book_name, 80, stdin);
printf("Enter the author name: ");
fgets(b[i].author, 80, stdin); 
printf("Enter the book ID: ");
scanf("%d",&b[i].book_id);
printf("Enter the book price: ");
scanf("%f",&b[i].price);
fflush(stdin);
}
printf("\nThe details of the book are:\n\n");
for(i = 0; i < 3; i++)
{
printf("The book name is: ");
puts(b[i].book_name);
printf("The author name is: ");
puts(b[i].author);
printf("The book ID is: %d\n",b[i].book_id);
printf("The book price is: %0.2f\n",b[i].price);
}
return 0;
}

Code-

Example of array of Structures in C

Output-

Output of array of Structures in C

7. Typedef in C

We have already discussehow typedef in C helps in simplifying the syntax of structures.

8. C Nested Structures

A nested structure is basically a structure within a structure. Sometimes we might encounter problems where simply the clubbing together of primitive data types might not help, rather we would require a more complex solution.

We might require the clubbing of 2 user-defined data types, such as the array of structures or nested structures.

Since we have already discussed what array of structures are and how to implement it, let’s move on towards nested structures.

Suppose we want to access the marks of a student in 3 subjects, namely physics chemistry and mathematics along with the details of the student such as his name, age, and gender.

We can solve this problem by creating two structures, one for accessing the marks in respective subjects and the other to access the student details.

The nested structure would somewhat look like this:

struct Marks
{
float physics;
float chemistry;
float mathematics;
};
struct Student
{
char name[20];
int age;
Marks m; // Here m is a variable for the structure Marks 
}; Student s; // Here s is a variable for the structure Student

Here, the main structure is Student within which we have declared another structure called Marks.

Here is a code in C that illustrates how a nested structure works with reference to the above-stated problem:

#include<stdio.h>
#include<string.h>
struct Marks
{
float physics;
float chemistry;
float mathematics;
};
struct Student
{
char name[20];
int age;
struct Marks m; // Here m is a variable for the structure Marks
}s; // Here s is a variable for the structure Student

int main()
{

printf("Welcome to DataFlair tutorials!\n\n");
printf("Enter student name: ");
fgets(s.name, 20, stdin);
printf("Enter student age: ");
scanf("%d",&s.age);
printf("\nEnter the marks in the following subjects:\n");
printf("Physics: ");
scanf("%f",&s.m.physics);
printf("Chemistry: ");
scanf("%f",&s.m.chemistry);
printf("Mathematics: ");
scanf("%f",&s.m.mathematics);
printf("\nThe student details are:\n\n");
printf("Physics: %0.2f\n",s.m.physics);
printf("Chemistry: %0.2f\n",s.m.chemistry);
printf("Mathematics: %0.2f\n",s.m.mathematics);
return 0;
}

Code-

Example of C Nested Structures 

Output-

Output of C Nested Structures 

9. Array within a Structure

We can solve the same problem using the concept of arrays within a structure.

Key takeaway: It is important to note that the array of structures and array within a structure are 2 entirely different concepts.

Discover the important concept of Multi-dimensional Arrays

This is how you could have used array within a structure since marks of the 3 subjects would be of similar data type, that is, float.

struct Student
{
char name[30];
int age;
float marks[3];

/* Index 0: physics, Index 1- chemistry, Index 2- mathematics */

}s;

This is how you would access the array within a structure:

S.marks[1] // To access the marks obtained in chemistry.

Here is a code in C that illustrates the use of array within a structure to implement the use of array within a structure:

#include<stdio.h>
struct Student
{
char name[20];
int age;
float marks[3]; // Array within a structure
}s; // Here s is a variable for the structure Student

int main()
{
int i;
printf("Welcome to DataFlair tutorials!\n\n");
printf("Enter student name: ");
fgets(s.name, 20, stdin);
printf("Enter student age: ");
scanf("%d",&s.age);
printf("Enter the marks in physics, chemistry and mathematics respectively: ");
for(i=0;i<3;i++)
{
scanf("%f",&s.marks[i]);
}
printf("\nThe student details are:\n\n");
puts(s.name);
printf("%d\n",s.age);
printf("The marks in physics, chemistry and mathematics:\n");
for(i=0;i<3;i++)
{
printf("%0.2f\n",s.marks[i]);
}
return 0;
}

Code-

 Array within a Structure with Example

Output-

Output of Array within a Structure

10. Structures to a Function

Before discussing this topic, it is important to have a crystal clear understanding of functions in C.

We already know how to pass arguments of different data types to a function. Since a structure is nothing but a user-defined data type, it is not an alien concept to pass a structure to a function. We pass structures to a function when the structure is local to a function.

We can pass structures to a function in 2 ways:

  • Call by value
  • Call by reference

We will mainly discuss how to pass structures to a function using call by value and then later on briefly discuss how to do the same using call by reference.

Suppose we have a structured box with data members as its dimensions, namely, length, width and height and we wish to create a function to display the dimensions of the box, we need to pass the structures to the function as an argument.

Here is a code in C that illustrates passing a structure to a function with reference to the above-stated problem:

#include<stdio.h>
struct box
{
float length;
float width;
float height;
};
void display(struct box b);
int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

struct box b;
{
printf("Enter the dimensions of the box:\n\n");
printf("Length: ");
scanf("%f",&b.length);
printf("Width: ");
scanf("%f",&b.width);
printf("Height: ");
scanf("%f",&b.height);
display(b);
}
return 0;
}
void display(struct box b)
{
printf("Length: %0.2f\n", b.length);
printf("Width: %0.2f\n", b.width);
printf("Height: %0.2f\n", b.height);
}

Code-

Example of structure to a function in C

Output-

Output of structure to a function

Another point to be noted is that structures to a function can be passed in another way. In the previous method, we passed the entire structure to the function. The alternate method proves to be more flexible as it allows to pass individual data members of the structure to the function.

We can implement the above-stated problem in this manner:

struct box
{
float length;
float width;
float height;
}b;

Then,

void output(b.length, b.width,b.height)

Let us consider a problem where structures to a function are passed by the call by reference method to calculate the sum of 2 distances.

11. Structures using Pointers

Before discussing this topic, it is important to have a crystal clear understanding of pointers in C.

The C programming language gives the programmer the provision to access structures with the help of pointers.

We can access structures with the help of pointers in the following manner:

struct structure_name
{
data_type data_member1;
data_type data_member2;
data_type data_member3;
data_type data_membern;
};
int main()
{
struct structure_name *p; // Here *p is a pointer to the structure structure_name
return 0;
}

12.How to access Structures through Pointers?

Here is a code in C that illustrates how structures can be accessed with the help of pointers with reference to the box problem discussed earlier in the previous section.

#include <stdio.h>
struct box
{
float length;
float width;
float height;
}b;


int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

struct box *box_pointer, box1;
box_pointer = &box1; 
printf("Enter the dimensions of the box:\n\n");
printf("Length: ");
scanf("%f", &box_pointer->length);
printf("Width: ");
scanf("%f", &box_pointer->width);
printf("Height: ");
scanf("%f", &box_pointer->height);

printf("The dimensions of the box are:\n");
printf("Length: %0.2f\n", box_pointer->length);
printf("Width: %0.2f\n", box_pointer->width);
printf("Height: %0.2f\n", box_pointer->height);
return 0; 
}

Code

Example of access Structures through Pointers in C

Output-

Output of access Structures through Pointers

13. Structures in C vs C++

We already know that C++ refers to C with classes. One of the salient features of C++ is that it supports object-oriented programming. OOP supports the implementation of classes.

Classes are not available in C and hence it is safe to say that in C++, a structure is a class that can be declared with the help of the keyword struct.

The striking difference between a structure and a class is that a structure is public by default, that is, it can be accessed anywhere inside the entire program, whereas a class is private by default but can be changed to public or protected mode as per the user’s requirement.

To be precise, a structure is a collection of only data members and a class is a collection of data members plus member functions.

In this way, we can differentiate both of them-

Structures in C

struct structure_name
{

// Data member declarations

data_type data_member1;
data_type data_member2;
data_type data_member3;
.
.
.
data_type data_membern;
};

Structures in C++

struct structure_name
{
[public:] [private:] [protected:]

/* Data members and member functions declarations */

data_type data_member1;
data_type data_member2;
data_type data_member3;
.
.
.
data_type data_membern;

return_type member_function1;
return_type member_function2;
return_type member_function3;
.
.
.
return_type member_functionn;
};

Typecasting in C – An interesting and important concept of C

Quiz on Structures in C

Summary

In this tutorial, we paved the way to optimize data representation by mastering the concepts of structures by learning how to group together logically related variables. We discussed structures in detail by shedding light on its significance and the various applications using arrays, functions, and pointers.

Furthermore, if you have any query, feel free to ask in the comment section.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *