Structure

C has built-in primitive and derived data types. Still, not all real-world problems can be solved using those types. You need a custom data type for different situations.
For example, if you need to store 100 student record that consists 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 the student record, it says seem feasible to you. But, think how cumbersome it would be to manage student record with more than 10 fields, in separate variables for the 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 the C programming language.

What is the structure in C?

A 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 the name, age and mobile. Creating a structure type will allow you to handle all properties (fields) of a student with a single variable, instead of handling it separately.


Syntax to define a structure

struct structure_name
{
    member1_declaration;
    member2_declaration;
    ...
    ...
    memberN_declaration;
};
Here, structure_name is the name of our custom type. memberN_declaration is structure member i.e. a 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 structuring definition

  • You must terminate the structure definition with a semicolon;.
  • You cannot assign the value to members inside the structure definition, it will cause a compilation error. Since you are defining type you aren't associating data.
    For example, the 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 a structure object (structure variable)?

A data type is useless without variables. A data type defines various properties of 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 the 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 the luxury to declare structure variable anywhere in the program based on the structure scope. If the structure is defined in global scope, we can declare its variable in the main() function, any other functions and in the global section too.
Syntax:
struct structure_name structure_variable;
For the 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 the 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 the 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 the 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 😉

No comments

Powered by Blogger.