Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Define Structure in C

Last Updated on April 13, 2023 by Prepbytes

A structure in C enables programmers to group different types of variables together under a single name. Structure in C language is a very powerful feature that allows for the creation of more complex data structures. In this article, we will discuss the structure definition in C, how to declare a structure in C, usage of structure in C, and some examples, and at the end, we will also see what is a nested structure in C. So, without any further delay, let’s move on to our next section.

What is Structure in C?

In C language, a user-defined data type called structure allows us to store a variety of distinct data types. The word "member" refers to each component of a structure. Because they can contain different types of information, structures can emulate the usage of classes and templates.

The structure is specified using the struct keyword. Let’s look at the syntax to define structure in C language.

struct structure_name   
{  
    data_type member1;  
    data_type member2;  
    .  
    .  
    data_type memeberN;  
};  

Let’s look at an example of how to define structure in C example for an entity employee.

struct employee  
{   int id;  
    char name[20];  
    float salary;  
};

The memory allocation for the structure employee defined in the preceding example is displayed in the next image.

In this case, a struct is a keyword; the employee is the structure’s name; and id, name, and salary are its members or fields. Let’s interpret it using the following diagram:

Define structure in C

Structure variables must first be defined before being created. Structures may be defined using the struct keyword.

Syntax:-

struct name_of_the_structure 
{
    data_type member1;
    data_type member2;
    ...
    data_type memberN;
};

Example of C Structures

struct bill
{
   float amount;
   int id;
   char address[100];
};

How to Declare structure variable?

To make it simple to access a structure member, we can create a variable for the structure. Structure variables can be declared in one of two ways:

  1. By using the struct keyword in the main() method.
  2. By declaring a variable when the structure is defined.

1st way:
Let’s look at an example of using the struct keyword to define structure variable. Declaring it within the main function is appropriate.

struct employee  
{   int id;  
    char name[50];  
    float salary;  
};  

Put the provided code within the main() method at this point.

struct employee e1, e2;  

The values kept in the structure can be accessed using the variables e1 and e2. Here, e1 and e2 may be handled similarly to Java and C++ objects.

2nd way:
Let’s see a different approach to declaring variables as the structure is being defined.

struct employee  
{   int id;  
    char name[50];  
    float salary;  
}e1,e2;  

Which strategy is best?
Use the first method if some variables are not fixed. You have the freedom to declare the structure variable several times.
Use the second strategy if the number of variables is fixed. Declaring a variable in the main() method saves you code.

Accessing members of the structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let’s look at the code for the (member) operator to access the id member of the p1 variable.
p1.id

Why use structure?

There are conditions where we need to keep more than one attribute for an entity in the C language. An entity need not include all the information of a single type. It is capable of having various properties from various data types. As an illustration, a student object may have a name (string), roll number (int), and marks (float). We have the following methods for storing this sort of student-related information:

  • Construct individual arrays for storing names, roll numbers, and marks.
  • Use a special data structure to store the collection of different data types.

C Structure example

Let’s see a simple structure in C example.

#include<stdio.h>  
#include <string.h>    
struct employee      
{   int id;      
    char name[50];      
}e1;  //declaring e1 variable for structure    
int main( )    
{    
   //store first employee information    
   e1.id=101;    
   strcpy(e1.name, "Abhishek Sharma");//copying string into char array    
   //printing first employee information    
   printf( "employee 1 id : %d\n", e1.id);    
   printf( "employee 1 name : %s\n", e1.name);    
return 0;  
}

Output

employee 1 id: 101
employee 1 name: Abhishek Sharma

Explanation: The above program demonstrates the use of structure in C programming language. First, a structure is defined using the keyword "struct" with the name "employee". It has two member variables – an integer "id" and a character array "name" of size 50. Next, a structure variable "e1" is declared for the "employee" structure. In the main function, the program stores information about the first employee in the "e1" structure. The "id" value of the employee is set to 101 using the dot (.) operator. The "name" of the employee is set using the strcpy() function, which copies the string "Abhishek Sharma" into the "name" character array of the "e1" structure.

Nested Structure in C

Complex data types can be generated by nesting one structure inside another utilizing C’s functionality. For instance, we could need to keep the address of an employee for an object in a structure. Street number, city, state, and pin code are additional subparts that can be included in the attribute address. As a result, in order to save the employee’s address, we must nest the structure in which the address is stored within the structure that contains the employee’s address. Consider the program below.

#include<stdio.h>  
struct address   
{  
    char city[20];  
    int pin;  
    char phone[14];  
};  
struct employee  
{  
    char name[20];  
    struct address add;  
};  
void main ()  
{  
    struct employee emp;  
    printf("Enter employee information?\n");  
    scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);  
    printf("Printing the employee information....\n");  
    printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);  
}

Output

Abhay
Delhi
123456
1234567890
Enter employee information?
Printing the employee information....
name: Abhay
City: Delhi
Pincode: 123456
Phone: 1234567890

Explanation: This program demonstrates the use of nested structure in C language. The code starts by defining two structures – "address" and "employee". The "address" structure has three member variables – a character array "city" of size 20, an integer "pin", and a character array "phone" of size 14. The "employee" structure has two member variables – a character array "name" of size 20 and an "address" structure variable "add". In the main function, the program declares an "employee" structure variable "emp". Then, it prompts the user to enter the employee information using the printf() function. The scanf() function is used to read the input values into the "emp" structure members – "name", "add.city", "add.pin", and "add.phone".

The structure can be nested in the following ways.

  1. By separate structure
  2. By Embedded structure

1) Separate structure
In this case, we build two structures, but the dependent structure must be a member of the primary structure. Consider the case below.

struct Date  
{  
   int dd;  
   int mm;  
   int yyyy;   
};  
struct Employee  
{     
   int id;  
   char name[20];  
   struct Date doj;  
}emp1;  

As you can see, the variable doj (date of joining) is of type Date. In this case, doj is a part of the Employee hierarchy. The Date structure may be applied in a variety of structures in this fashion.

2) Embedded structure
We can declare the structure inside the structure due to the embedded structure. Since it cannot be utilized in many data structures, it takes fewer lines of code. Consider the case below.

struct Employee  
{     
   int id;  
   char name[20];  
   struct Date  
    {  
      int dd;  
      int mm;  
      int yyyy;   
    }doj;  
}emp1;  

Accessing Nested Structure in C

We can access the member of the nested structure in C by Outer_Structure.Nested_Structure.member as given below:

e1.doj.dd  
e1.doj.mm  
e1.doj.yyyy  

Nested Structure in C example

Let’s look at a straightforward example of a nested structure in C.

#include <stdio.h>  
#include <string.h>  
struct Employee  
{     
   int id;  
   char name[20];  
   struct Date  
    {  
      int dd;  
      int mm;  
      int yyyy;   
    }doj;  
}e1;  
int main( )  
{  
   //storing employee information  
   e1.id=101;  
   strcpy(e1.name, "Abhay");//copying string into char array  
   e1.doj.dd=10;  
   e1.doj.mm=11;  
   e1.doj.yyyy=2014;  
  
   //printing first employee information  
   printf( "employee id : %d\n", e1.id);  
   printf( "employee name : %s\n", e1.name);  
   printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
   return 0;  
}

Output

employee id: 101
employee name: Abhay
employee date of joining (dd/mm/yyyy): 10/11/2014

Explanation: This program demonstrates the use of nested structure in C programming language, specifically in the context of storing and printing the date of joining of an employee along with their other information. The code defines a structure named "Employee" which has three member variables – an integer "id", a character array "name", and another structure "Date" which has three integer member variables – "dd" (day), "mm" (month), and "yyyy" (year). In the main function, the program declares an "Employee" structure variable "e1". It then stores the employee information such as "id", "name", and "date of joining" into their respective member variables of the "e1" structure using assignment statements and strcpy() function to copy the string.

Conclusion
In this article, we have taught the structure in C language, you have learned the basics of structure in C programming, and Structure definition in C language. You started with a small introduction to a structure in C and moved ahead to discuss the uses of a structure in C. Next, you learned about the syntax of structures, how to declare and initialize a structure in C, and how to access the elements of a structure in C.

FAQs

Here are some frequently asked questions on structure in C language.

Q1: What is the purpose of using a structure in C?
Ans: The purpose of using structures in C is to group related data together to make it easier to work with, manage, and organize.

Q2: Can you have arrays as members of a structure in C?
Ans: Yes, you can have arrays as members of a structure in C.

Q3: Can you have structures as members of a structure in C?
Ans: Yes, you can have structures as members of a structure in C.

Q4: Can you have pointers as members of a structure in C?
Ans: Yes, you can have pointers as members of a structure in C.

Q5: How do you pass a structure to a function in C?
Ans: You can pass a structure to a function in C by using the structure name as the argument.

Q6: Can you return a structure from a function in C?
Ans: Yes, you can return a structure from a function in C.

Q7: How do you compare two structures in C?
Ans: You can compare two structures in C by comparing each of their members.

Leave a Reply

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