Structure in C

At times, during programming, there is a need to store multiple logically related elements under one roof. For instance, an employee’s details like name, employee number, and designation need to be stored together. In such cases, the C language provides structures to do the job for us. 

Structure_in_C_1

A structure can be defined as a single entity holding variables of different data types that are logically related to each other. All the data members inside a structure are accessible to the functions defined outside the structure. To access the data members in the main function, you need to create a structure variable.

Now, lets get started with Structure in C programming.

Why Do We Use Structures in C?

Structure in C programming is very helpful in cases where we need to store similar data of multiple entities. Let us understand the need for structures with a real-life example. Suppose you need to manage the record of books in a library. Now a book can have properties like book_name, author_name, and genre. So, for any book you need three variables to store its records. Now, there are two ways to achieve this goal. 

The first and the naive one is to create separate variables for each book. But creating so many variables and assigning values to each of them is impractical. So what would be the optimized and ideal approach? Here, comes the structure in the picture. 

We can define a structure where we can declare the data members of different data types according to our needs. In this case, a structure named BOOK can be created having three members book_name, author_name, and genre. Multiple variables of the type BOOK can be created such as book1, book2, and so on (each will have its own copy of the three members book_name, author_name, and genre). 

Moving forward, let’s he a look at the syntax of Structure in C programming

Add Another Star to Your Performance Evaluation

Learn from industry experts for FREEStart Learning
Add Another Star to Your Performance Evaluation

Syntax to Define a Structure in C

struct structName 

   // structure definition

   Data_type1 member_name1;

   Data_type2 member_name2;

   Data_type2 member_name2; 

}; 

Below is the description of Structure in C programming   

Description of the Syntax

  • Keyword struct: The keyword struct is used at the beginning while defining a structure in C. Similar to a union, a structure also starts with a keyword.

  • structName: This is the name of the structure which is specified after the keyword struct. 

  • data_Type: The data type indicates the type of the data members of the structure.  A structure can have data members of different data types.
  • member_name: This is the name of the data member of the structure. Any number of data members can be defined inside a structure. Each data member is allocated a separate space in the memory.

Next, let us see how to declare variable of structure in C programming

How to Declare Structure Variables?

Variables of the structure type can be created in C. These variables are allocated a separate copy of data members of the structure. There are two ways to create a structure variable in C.

  • Declaration of Structure Variables with Structure Definition

This way of declaring a structure variable is suitable when there are few variables to be declared. 

Syntax

struct structName 

   // structure definition

   Data_type1 member_name1;

   Data_type2 member_name2;

   Data_type2 member_name2;   

} struct_var1, struct_var2;

Example

struct bookStore

   // structure definition

   char storeName

   int totalBooks;

   char storeLicense[20];

} storeA, storeB;   // structure variables

The structure variables are declared at the end of the structure definition, right before terminating the structure. In the above example, storeA and storeB are the variables of the structure bookStore. These variables will be allocated separate copies of the structure’s data members that are- storeName, totalBooks, and storeLicense.

  • Declaration of Structure Variables Separately

This way of creating structure variables is preferred when multiple variables are required to be declared. The structure variables are declared outside the structure. 

Syntax

struct structName

   // structure definition

   Data_type1 member_name1;

   Data_type2 member_name2;

   Data_type2 member_name2; 

}; 

   struct structName struct_var1, struct_var2;

Example

struct bookStore

   // structure definition

   char storeName 

   int totalBooks;

   char storeLicense[20]; 

}; 

int main()

{

   struct bookStore storeA, storeB; // structure variables;

}

When the structure variables are declared in the main() function, the keyword struct followed by the structure name has to be specified before declaring the variables. In the above example, storeA and storeB are the variables of the structure bookStore. 

Next, let us see how to initialize member in Structure in C programming

How to Initialize Structure Members?

Structure members cannot be initialized like other variables inside the structure definition. This is because when a structure is defined, no memory is allocated to the structure’s data members at this point. Memory is only allocated when a structure variable is declared. Consider the following code snippet.

struct rectangle

   // structure definition 

   int length = 10;   // COMPILER ERROR:  cannot initialize members here.

   int breadth = 6;   // COMPILER ERROR:  cannot initialize members here. 

};

A compilation error will be thrown when the data members of the structure are initialized inside the structure. 

To initialize a structure’s data member, create a structure variable. This variable can access all the members of the structure and modify their values. Consider the following example which initializes a structure’s members using the structure variables.

struct rectangle

{

   // structure definition 

   int length;   

   int breadth;   

};

int main()

{

   struct rectangle my_rect; // structure variables;

   my_rect.length = 10;

   my_rect.breadth = 6;

}

In the above example, the structure variable my_rect is modifying the data members of the structure. The data members are separately available to my_rect as a copy. Any other structure variable will get its own copy, and it will be able to modify its version of the length and breadth. 

Moving forward, let us understand how to access elements in structure in C programming

How to Access Structure Elements?

The members of a structure are accessed outside the structure by the structure variables using the dot operator (.). The following syntax is used to access any member of a structure by its variable:

Syntax

structVariable.structMember

Example

The following example illustrates how to access the members of a structure and modify them in C. 

#include <stdio.h>

#include <string.h>

struct cube

{

   // data members

   char P_name[10];

   int P_age;

   char P_gender;

};

int main()

{

   // structure variables

   struct cube p1, p2;

   // structure variables accessing the data members.

   strcpy(p1.P_name, "XYZ");

   p1.P_age = 25;

   p1.P_gender = 'M';

   strcpy(p2.P_name, "ABC");

   p2.P_age = 50;

   p2.P_gender = 'F';

   // print the patient records.

   // patient 1

   printf("The name of the 1st patient is: %s\n", p1.P_name);

   printf("The age of the 1st patient is: %d\n", p1.P_age);

   if (p1.P_gender == 'M')

   {

      printf("The gender of the 1st patient is: Male\n");

   }

   else

   {

      printf("The gender of the 1st patient is: Female\n");

   }

   printf("\n");

   // patient 2

   printf("The name of the 2nd patient is: %s\n", p2.P_name);

   printf("The age of the 2nd patient is: %d\n", p2.P_age);

   if (p2.P_gender == 'M')

   {

      printf("The gender of the 2nd patient is: Male\n");

   }

   else

   {

      printf("The gender of the 2nd patient is: Female\n");

   }

   return 0;

}

Structure_in_C_2

In the above program, a structure named Patient is defined. It has three data members- P_name, P_age, and P_gender. These data members have not been allocated any space in the memory yet. The variables p1  and p2 are the structure variables declared in the main function. 

As soon as these variables are created, they get a separate copy of the structure’s members with space allocated to them in the memory. Both p1 and p2 are accessing their copies of the structure’s members to modify them using the dot operator. 

Next, let us understand how to pass function in structure in C programming language

How to Pass Structures to Functions in C?

As all the members of a structure are public in C, therefore they are accessible anywhere and by any function outside the structure. Functions accept structures as their arguments in a similar way as they accept any other variable or pointer. To pass a structure to a function, a structure variable is passed to the function as an argument. 

A structure variable can be passed to a function as an argument in the following three ways:

  • Passing Structure to a Function by Value

When a structure variable is passed by its value, a copy of the members is passed to the function. If the function modifies any member, then the changes do not affect the structure variable’s copy of members. The following example illustrates how to pass a structure variable to a function by value in C.

#include <stdio.h>

#include <string.h>

struct patient

{

   int ID;

   char name[10];

   char gender;

};

// function that accepts a structure variable as arguments.

void passByValue(struct patient p)

{

   p.ID = 102; // this modification does not affect P1's id.

   // print the details.

   printf(" The patient's ID is: %d \n", p.ID);

   printf(" The patient's name is: %s \n", p.name);

   printf(" The patient's gender is: %c \n", p.gender);

}

int main()

{

   struct patient P1;

   P1.ID = 101;

   strcpy(P1.name, "ABC");

   P1.gender = 'M';

   passByValue(P1); // pass structure variable by value.

   // P1's ID remains unaffected by the function's modification.

   printf("\n The original value of ID is: %d\n\n", P1.ID);

   return 0;

}

Structure_in_C_3 

In the above program, the function passByValue() accepts the structure’s variable P1 as an argument. This argument is passed by value. When the function makes a modification in the member ID, this modification does not affect the P1’s version of ID. The reason is that in the case of pass-by-value, only a copy of the members is passed to the function. So, any changes made by the function do not reflect in the original copy. 

  • Passing Structure to a Function by Reference

When a structure variable is passed by its reference, the address of the structure variable is passed to the function. This means the function does not get any copy, instead, it gets the reference or address of the structure variable’s members. 

If the function modifies any member, then the changes get reflected in the structure variable’s copy of members. Note that in pass-by-reference, the structure members can be accessed using the arrow operator (->).

The following example illustrates how to pass a structure variable to a function by reference in C.

#include <stdio.h>

#include <string.h>

struct patient

{

   int ID;

   char name[10];

   char gender;

};

// function that accepts a structure variable as arguments.

void passByReference(struct patient *p)

{

   p->ID = 102; // this modification reflects P1's id.

   // print the details.

   printf(" The patient's ID is: %d \n", p->ID);

   printf(" The patient's name is: %s \n", p->name);

   printf(" The patient's gender is: %c \n", p->gender);

}

int main()

{

   struct patient P1;

   P1.ID = 101;

   strcpy(P1.name, "ABC");

   P1.gender = 'M';

   passByReference(&P1); // pass structure variable by reference.

   // P1's ID gets affected by the function's modification.

   printf("\n The original value of ID is: %d\n\n", P1.ID);

   return 0;

}

Structure_in_C_4. 

In the above example, the function passByReference() accepts the structure’s variable P1 as an argument. This argument is passed by reference.  So, the function gets access to the location of the structure variable. When the function makes a modification in the member ID, this modification affects the P1’s version of ID. 

  • Declaring Structure Variables as Global

When a structure variable is declared as global, it can be accessed by any function in the program. There will be no need to pass the structure variable to the function. However, this is not advised as all the functions can modify the values of the structure variable’s copy of members. This also affects the data security in the program.

The following example illustrates how to declare a global structure variable in C and access it in functions.

#include <stdio.h>

#include <string.h>

struct patient

{

   int ID;

   char name[10];

   char gender;

};

// structure variable declared globally.

struct patient P1; 

void my_function()

{

   // print the details.

   printf(" The patient's ID is: %d \n", P1.ID);

   printf(" The patient's name is: %s \n", P1.name);

   printf(" The patient's gender is: %c \n\n", P1.gender);

}

int main()

{

   P1.ID = 101;

   strcpy(P1.name, "ABC");

   P1.gender = 'M';

   // no need to pass the structure variable

   // to the function as an argument.

   my_function();   // function call

   return 0;

}

Structure_in_C_5

In the above example, the structure variable P1 is declared as a global variable. Being a global variable, P1 is accessed by any function in the program. The function my_function() does not require P1 to be passed to it as an argument. It can directly access P1 and modify any structure member using P1.

Moving forward,  let us understand what is designated initialization in structure in C programming language.

What is Designated Initialization?

In the C99 standard, there is a unique feature that is not available in other standards like C90 or GNU C++. Designated initialization is supported for array, union, and structure in C. To understand the working of designated initialization, consider the following example of array initialization at the time of declaration.

int my_arr[5] = {10, 20, 30, 40, 50};

// my_arr[0] = 10, my_arr[1] = 20, ..., my_arr[5] = 50.

In the above array initialization, all array elements are initialized in the fixed order. This means that the element at index 0 is initialized first, then the index 1 element is initialized, and so on. 

These array elements can also be initialized in any random order, and this method is called designated initialization. Consider the following example which initializes the array elements in random order.

int a[5] = {[3] = 30, [2] = 20 }; 

// OR

int a[5] = {[3]30 , [2]20 };

The following program illustrates the designated initialization of a structure in C.

#include <stdio.h>

struct rectangle

{

   int length, breadth, height;

};

int main()

{

   // Examples of initialization using designated initialization

   struct rectangle r1 = {.breadth = 10, .height = 5, .length = 6};

   struct rectangle r2 = {.breadth = 20};

   printf("The values of r1 are: \n");

   printf("length = %d, breadth = %d, height = %d\n", r1.length, r1.breadth, r1.height);

   printf("The values of r2 are: \n");

   printf("length = %d, breadth = %d, height = %d\n\n", r2.length, r2.breadth, r2.height);

   return 0;

}

Structure_in_C_6. 

In the above example, the structure members- length, breadth, and height are initialized in a random order using the designated initialization. This type of initialization would throw an error in the compiler of other standards and even C++ does not support this functionality.

What is an Array of Structures?

Suppose you need to store the details of students like name, class, and roll number in your database. Now, the first thing that comes to your mind would be to create a structure variable and access the student details. This method is practical for a few students only, but what if the total number of students is 100 or something. It is not convenient to create 100 separate structure variables for 100 students. In such cases, we use an array of structures.

Just like other data types (mostly primitive), we can also declare an array of structures. An array of structures acts similar to a normal array. However, there is one thing to be kept in mind and that is the name of the structure followed by the dot operator(.) and the name of the array has to be mentioned to access an array element.

The following example illustrates the working of the array of structures in C.

#include <stdio.h>

// structure definition

struct Student

{

    // data members

    char name[10];

    int marks;

}; 

// declare an array of the structure Student.

struct Student stu[3];

int i, j; 

// function to read the values

// from the user and print them.

void print()

{

    // read input from the user.

    for (i = 0; i < 3; i++)

    {

        printf("\nEnter the record of Student %d\n", i + 1);

        printf("\nStudent name: ");

        scanf("%s", stu[i].name);

        printf("Enter Marks: ");

        scanf("%d", &stu[i].marks);

    }

    // print the details of each student.

    printf("\nDisplaying Student record\n");

    for (i = 0; i < 3; i++)

    {

        printf("\nStudent name is %s", stu[i].name);

        printf("\nMarks is %d", stu[i].marks);

    }

}

int main()

{

    // function call

    print();

    return 0;

}

Structure_in_C_7 

In the above example, we have created a structure Student that holds student names and marks. We have initialized an array stu of size 3 to get the names and marks of 3 students. Note that unlike the usual array in C, the array of structures in C is initialized by using the names of the structure as a prefix.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

What is a Structure Pointer?

A pointer structure is a variable that holds the address of the memory block of the structure. It is similar to other pointer variables like a pointer to an int or a pointer to a float. Consider the following code snippet.

struct point

{

    // data member

   int num;

};

 int main()

{

    // struct1 variable var

    struct struct1 var;

    // pointer variable

    struct point *ptr = &var;

    return 0;

}

Here, var is the structure variable of struct1 and ptr is the pointer variable. The ptr is storing the address of the var. In the case of a pointer to a structure, the members can be accessed using the arrow (->) operator. The following example illustrates the pointer to a structure in C.

#include<stdio.h>

struct myStruct

{

   int x, y;

};  

int main()

{

   struct myStruct var1 = {1, 2};  

   // var2 is a pointer to structure var1.

   struct myStruct *var2 = &var1;  

   // Accessing data members of myStruct using a structure pointer.

   printf("%d %d", var2->x, var2->y);

   return 0;

}

Structure_in_C_8

In the above example, the structure myStruct has a variable var1. The var2 is the pointer variable that stores the address of this structure variable.

Nested Structures

The C programming language allows the nesting of the structure. This can be done by using one structure into the body of another structure. Nesting of multiple separate structures enables the creation of complex data types.

For instance, you need to store the information of multiple students. Now the data members of the structure may be student name, student class, and student roll number. Now class can have multiple subparts like standard, section, and stream. Such types of cases can use nested structures to a great extent. 

A structure in C can be nested in two ways:

  • By Creating a Separate Structure

We can create two separate, let's say struct1 and struct2 structures, and then nest them. If you want to nest struct2 in struct1, then it is necessary to create struct2  variable inside the primary structure i.e., struct1. The nested structure would be used as a data member of the primary structure. Consider the following code snippet.

// structure 2

struct struct2

{

    // data members of struct2

}; 

// structure 1

struct struct1

{

    // data members of struct1 

    // struct2 variable

    struct struct2 obj2; 

}obj1; // struct1 variable 

Here, struct1 is the primary structure and struct2 is the secondary one. It is clearly observable that the variable of struct2 is created inside struct1.

Example

The following example illustrates the nesting of a structure in C by creating a separate structure.

#include <stdio.h>

// structure 2

struct class_details

{

    int standard;

    char section;

    char stream[20];

}; 

// structure 1

struct Student

{

    char name[20];

    int roll_num;

    // nested structure 2 in structure 1

    // class_details variable Class

    struct class_details Class;

};

int main()

{

    // Student variable stu

    struct Student stu; 

    // read the input from user

    printf("Enter details of the student: \n");

    scanf("%s %d %d %c %c",

          &stu.name,

          &stu.roll_num,

          &stu.Class.standard,

          &stu.Class.section,

          &stu.Class.stream); 

    // display the input info

    printf("The Student's details are: \n");

    printf("Name: %s\nRoll_num: %d\nStandard: %d\nSection: %c\nStream %s: ",

           stu.name,

           stu.roll_num,

           stu.Class.standard,

           stu.Class.section,

           stu.Class.stream); 

    return 0;

}

Structure_in_C_9

In the above example, we created two structures, Student and class_details. The structure Student contains the basic information about the student while the structure class_details contains the information about the class of the student specifically. The class_details structure is nested inside the Student structure by creating the object inside it so that all the data members of the class_details can be accessed by the Student structure too. 

  • By Creating Embedded Structure

In this method, instead of creating independent structures, if create a structure within a structure. This takes the independence of a structure and makes it inaccessible as well as useless for other structures. However, in this way, you have to write less code and the program will be cleaner. Consider the following code snippet.

// structure 1

struct struct1

{

    // data members of struct1 

    // structure 2

    struct struct2

    {

        // data members of struct2 

    } obj2; // struct2 variable 

} obj1;     // struct1 variable

Here, struct2 is created inside struct1 just like a data member, and the struct2 variable is also defined inside the primary structure.

Example

The following example illustrates the nesting of a structure in C by creating an embedded structure.

#include <stdio.h>

// structure 1

struct Student

{

    char name[20];

    int roll_num; 

    // nested structure 2 in structure 1

    // structure 2

    struct class_details

    {

        int standard;

        char section;

        char stream[20];

    };

    // class_details variable Class

    struct class_details Class;

}; 

int main()

{

    // Student variable stu

    struct Student stu; 

    // read the input from user

    printf("Enter details of the student: \n");

    scanf("%s %d %d %c %c",

          &stu.name,

          &stu.roll_num,

          &stu.Class.standard,

          &stu.Class.section,

          &stu.Class.stream); 

    // display the input info

    printf("The Student's details are: \n");

    printf("Name: %s\nRoll_num: %d\nStandard: %d\nSection: %c\nStream %s: ",

           stu.name,

           stu.roll_num,

           stu.Class.standard,

           stu.Class.section,

           stu.Class.stream); 

    return 0;

}

Structure_in_C_10

Here, the logic and the data members are exactly the same as in the previous example. The major difference here is that instead of creating a separate structure of details of the class, we created an embedded structure. You can observe that even though the methods are different, the outputs of both methods are exactly the same.

Limitations of Structure in C Programming

Up to this point in this article, it must be pretty clear to you how important and useful structures in C are. However, everything that possesses some advantages has some limitations as well and so do structures. In this section, we are going to discuss some of these limitations.

  • The struct data type can not be used as a built-in data type. If you try to use it as a built-in data type, the compiler will throw an error.
  • Arithmetic operators can not be implemented on structure variables. Consider the following code as an example.

#include <stdio.h>

struct number

{

    float x;

};

int main()

{

    struct number n1, n2, n3;

    n1.x = 4;

    n2.x = 3;

    n3 = n1 + n2;

    return 0;

}

Structure_in_C_11. 

  • Data hiding is not possible in structures. Structure in C does not permit any data members to be hidden and allows every function to access them.
  • You can not define member functions inside a structure in C. Structure in C only allows the definition of data members inside it and prohibits functions.
  • The concept of access modifiers is absent in the C language. So data members in a structure are always public to all the functions outside that structure.
  • Structure in C does not permit the creation of static members and constructors inside its body.

That was all about Structure in C Programming.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Final Thoughts!

To sum up, in this article Structure in C Programming, you have learned the basics of a structure in C programming. 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.  

Moving ahead, in the Structure in C Programming article you learned other important concepts such as designated initialization of a structure in C, array of structures, and a pointer to a structure. You ended the article with a brief explanation of nested structures and limitations of a structure in C. 

Why stop here? You can try out Simplilearn’s 9-month certification training on Full Stack Web Development. In this course, you will be able to learn important software development aspects such as Agile methodologies, DevOps culture and other important web development tools such as Java and it’s frameworks including Hibernate, Spring, etc. You will learn CSS, HTML, JS, and all other important tools that will make you a professional full stack developer. 

If you have a knack for learning new technologies periodically, you should check out Simplilearn’s complete list of free online courses. If you have any queries in this “Structure in C Programming” article or suggestions for us, please mention them in the comment box and our experts answer them for you as soon as possible.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.