Structures in C programming, need and use

Structures in C, is an advance and most popular topic in C language. It facilitates you to design your custom data type. In this tutorial, we will learn about structures in C its need, how to declare, define and access structures.

Need of structures in C?

C has built in primitive and derrived data types. Still not all real world problems can be solved using those types. You need custom data type for different situations.

For example, if you need to store 100 student record that consist of name, age and mobile number. To code that you will create 3 array variables each of size 100 i.e. name[100], age[100], mobile[100]. For three fields in student record it say seem feasible to you. But, think how cumbersome it would be to manage student record with more than 10 fields, in separate variables for single student.

To overcome this we need a user defined data type. In this tutorial I am going to explain how easily we will deal with these situations using structures in C programming language.

What is structure in C?

Structure is a user defined data type. It is a collection of different data type, to create a new data type.

For example, You can define your custom type for storing student record containing name, age and mobile. Creating structure type will allow you to handle all properties (fields) of student with single variable, instead of handling it separately.

How to declare, define and access structure members?

To declare or define a structure, we use struct keyword. It is a reserved word in the C compiler. You must only use it for structure or its object declaration or definition.

Syntax to define a structure

struct structure_name
{
    member1_declaration;
    member2_declaration;
    ...
    ...
    memberN_declaration;
};

Here, structure_name is name of our custom type. memberN_declaration is structure member i.e. variable declaration that structure will have.

Example to define a structure

Let us use our student example and define a structure to store student object.

struct student
{
    char name[40];        // Student name
    int  age;             // Student age
    unsigned long mobile; // Student mobile number
};

Points to remember while structure definition

  • You must terminate structure definition with semicolon ;.
  • You cannot assign value to members inside the structure definition, it will cause compilation error. Since you are defining type you aren't associating data.

    For example, following is an invalid structure definition.

    struct student
    {
        char name[40] = "Raj";
        int  age      = 26;
        unsigned long mobile = 9891000033;
    };
  • You can define a structure anywhere like global scope (accessible by all functions) or local scope (accessible by particular function).
  • Structure member definition may contain other structure type.

How to create structure object (structure variable)?

A data type is useless without variables. A data type defines various properties about data stored in memory. To use any type we must declare its variable. Hence, let us learn how to create our custom structure type objects also known as structure variable.

In C programming, there are two ways to declare a structure variable:

  1. Along with structure definition
  2. After structure definition

Declaration along with the structure definition

Out of two ways to declare structure variable. You can declare a structure variable along with structure before terminating the structure definition.

Syntax:

struct structure_name
{
    member1_declaration;
    member2_declaration;
    ...
    ...
    memberN_declaration;
}structure_variable;

So, if you want to declare student type object along with student structure definition you can use this approach.

struct student
{
    char name[40];        // Student name
    int  age;             // Student age
    unsigned long mobile; // Student mobile number
}student1;

Declaration after structure definition

The other way to declare, gives you luxury to declare structure variable anywhere in program based on the structure scope. If structure is defined in global scope, we can declare its variable in main() function, any other functions and in the global section too.

Syntax:

struct structure_name structure_variable;

For above example, if we want to declare its variable with name student1, it will be declared as given below:

struct student
{
    char name[40];        // Student name
    int  age;             // Student age
    unsigned long mobile; // Student mobile number
};

// Declare student variable
struct student student1;

How to access structure members (data)?

You created structure and its variable. But since structure is a complex data type, you cannot assign any value directly to it using assignment operator. You must assign data to individual structure members separately.

C supports two operators to access structure members, using a structure variable.

Dot/period operator (.) in C

Dot/period operator also known as member access operator. We use dot operator to access members of simple structure variable.

Syntax:

structure_variable.member_name;

Example:

// Assign age of student1
student1.age = 26;

Arrow operator (->) in C

Since structure is a user defined type and you can have pointers to any type. Hence, you may also create pointers to structure.

In C language it is illegal to access a structure member from a pointer to structure variable using dot operator. We use arrow operator -> to access structure member from pointer to structure.

Syntax:

pointer_to_structure->member_name;

Example:

// Student2 is a pointer to student type
student2->age = 29;

Example program to demonstrate declare, define and access structure members

In this example, we will declare a structure type, create structure object and access structure members. I will show how to use both dot and arrow operator to access structure members.

/**
 * C program to demonstrate structures.
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


// Student type definition
struct student
{
    char name[40];              // Student name
    int  age;                   // Student age
    unsigned long long mobile;  // Student mobile number
};


int main()
{
    struct student student1;    // Simple structure variable
    struct student *student2;   // Pointer to student
    

    // Initialize pointer to student through dynamic memory allocation
    student2 = (struct student*) malloc(sizeof(struct student));
    
    // Input data in structure members using dot operator
    printf("Enter student name: ");
    fgets(student1.name, 40, stdin);

    printf("Enter student age: ");
    scanf("%d", &student1.age);

    printf("Enter student mobile: ");
    scanf("%llu", &student1.mobile);

    // Eat new line from input buffer
    getchar();

    printf("\nStudent using simple structure variable.\n");
    printf("Student name: %s\n",         student1.name);
    printf("Student age: %d\n",          student1.age);
    printf("Student mobile: %llu\n\n",   student1.mobile);



    // Input data in pointer to structure type using arrow operator
    printf("Enter student name: ");
    fgets(student2->name, 40, stdin);

    printf("Enter student age: ");
    scanf("%d", &student2->age);

    printf("Enter student mobile: ");
    scanf("%llu", &student2->mobile);

    printf("Student using pointer to structure variable.\n");
    printf("Student name: %s\n",        student2->name);
    printf("Student age: %d\n",         student2->age);
    printf("Student mobile: %llu\n",    student2->mobile);


    // Clear memory that was alloacted dynamically
    free(student2);
    
    return 0;
}
Output

Enter student name: Pankaj
Enter student age: 27
Enter student mobile: 7004544121

Student using simple structure variable.
Student name: Pankaj

Student age: 27
Student mobile: 7004544121

Enter student name: Prakash
Enter student age: 21
Enter student mobile: 9900445441
Student using pointer to structure variable.
Student name: Prakash

Student age: 21
Student mobile: 9900445441

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>