Structure in C language

 

1. Introduction to Structure in C

In C programming, a structure (struct) is a user-defined data type that allows you to group variables of different data types under a single name. Unlike arrays, which store elements of the same data type, structures can store elements of different data types together.

Structures are very useful when you want to represent real-world entities such as:

  • Student records (name, roll number, marks)
  • Employee details (ID, salary, department)
  • Date (day, month, year)
  • Book (title, author, price)

The keyword used to define a structure in C is:

struct

2. Why Do We Need Structures?

In real-life programming, we often need to store related data together. For example, suppose you are creating a student management system. For each student, you need:

  • Name (string)
  • Roll number (int)
  • Marks (float)

If you use separate variables for each student, it becomes confusing and difficult to manage. Structures solve this problem by grouping related variables.

Advantages of Structures:

  1. Logical grouping of related data.
  2. Improves code readability.
  3. Makes data handling easier.
  4. Useful in file handling and database-like programs.
  5. Used in complex data structures like linked lists, trees, and graphs.

3. Syntax of Structure

The general syntax for defining a structure is:

struct structure_name {
    data_type member1;
    data_type member2;
    data_type member3;
};

Example:

struct Student {
    int roll;
    char name[50];
    float marks;
};

Here:

  • Student is the structure name.
  • roll, name, and marks are structure members.

4. Declaring Structure Variables

After defining a structure, you need to declare variables of that structure type.

Method 1: After Structure Definition

struct Student s1, s2;

Method 2: During Structure Definition

struct Student {
    int roll;
    char name[50];
    float marks;
} s1, s2;

5. Accessing Structure Members

Structure members are accessed using the dot (.) operator.

Example:

#include <stdio.h>

struct Student {
    int roll;
    char name[50];
    float marks;
};

int main() {
    struct Student s1;

    s1.roll = 101;
    s1.marks = 85.5;

    printf("Roll: %d\n", s1.roll);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

6. Initialization of Structure

You can initialize a structure at the time of declaration.

Example:

struct Student s1 = {101, "Rahul", 90.5};

Or using designated initializers (C99):

struct Student s1 = {
    .roll = 101,
    .name = "Rahul",
    .marks = 90.5
};

7. Array of Structures

When we need to store multiple records, we use an array of structures.

Example:

struct Student s[3];

Now s[0], s[1], and s[2] represent different students.

Program Example:

#include <stdio.h>

struct Student {
    int roll;
    float marks;
};

int main() {
    struct Student s[2];

    for(int i = 0; i < 2; i++) {
        printf("Enter roll and marks: ");
        scanf("%d %f", &s[i].roll, &s[i].marks);
    }

    for(int i = 0; i < 2; i++) {
        printf("Roll: %d, Marks: %.2f\n", s[i].roll, s[i].marks);
    }

    return 0;
}

8. Nested Structures

A structure inside another structure is called a nested structure.

Example:

struct Date {
    int day;
    int month;
    int year;
};

struct Student {
    int roll;
    char name[50];
    struct Date dob;
};

Accessing nested members:

s1.dob.day = 15;

9. Structure and Functions

Structures can be passed to functions in three ways:

1. Passing Individual Members

void display(int roll, float marks);

2. Passing Entire Structure (Call by Value)

void display(struct Student s);

3. Passing Structure by Reference (Using Pointer)

void display(struct Student *s);

Example using pointer:

void display(struct Student *s) {
    printf("Roll: %d\n", s->roll);
}

Note:

  • -> is called arrow operator.
  • Used when accessing structure members through pointer.

10. Pointer to Structure

A pointer can point to a structure variable.

struct Student s1;
struct Student *ptr;

ptr = &s1;

Accessing members:

ptr->roll = 101;

OR

(*ptr).roll = 101;

Arrow operator is more convenient.


11. Typedef with Structure

To avoid writing struct again and again, we use typedef.

Example:

typedef struct {
    int roll;
    float marks;
} Student;

Student s1;

Now we can directly use Student instead of struct Student.


12. Structure Padding and Memory Allocation

Structure size is not always the sum of member sizes. The compiler may add padding bytes to align data properly in memory.

Example:

struct Test {
    char a;   // 1 byte
    int b;    // 4 bytes
};

Even though total is 5 bytes, actual size may be 8 bytes due to padding.

To check size:

printf("%lu", sizeof(struct Test));

Padding improves performance but increases memory usage.


13. Self-Referential Structure

A structure that contains a pointer to itself is called a self-referential structure.

Example:

struct Node {
    int data;
    struct Node *next;
};

This is mainly used in linked lists.


14. Structure vs Union

Feature Structure Union
Memory Separate memory for each member Shared memory
Size Sum of members (with padding) Size of largest member
Usage Store different values simultaneously Store one value at a time

15. Structure in File Handling

Structures are widely used in file handling to store records.

Example:

fwrite(&s1, sizeof(s1), 1, fp);
fread(&s1, sizeof(s1), 1, fp);

Used in:

  • Student management system
  • Employee payroll system
  • Library system

16. Applications of Structure

  1. Database record management
  2. Linked lists
  3. Trees and graphs
  4. File systems
  5. Network packets
  6. Game development
  7. Operating systems

17. Common Mistakes

  1. Forgetting semicolon after structure definition.
  2. Not using struct keyword (without typedef).
  3. Incorrect use of pointer and arrow operator.
  4. Memory padding misunderstanding.
  5. Not initializing structure members.

18. Real-Life Example Program

#include <stdio.h>

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

int main() {
    Employee e1;

    printf("Enter ID, Name and Salary: ");
    scanf("%d %s %f", &e1.id, e1.name, &e1.salary);

    printf("\nEmployee Details:\n");
    printf("ID: %d\n", e1.id);
    printf("Name: %s\n", e1.name);
    printf("Salary: %.2f\n", e1.salary);

    return 0;
}

19. Key Points for Exam Revision

  • Structure groups different data types.
  • Keyword: struct
  • Access operator: .
  • Pointer access operator: ->
  • Use typedef for simplicity.
  • Supports nesting.
  • Supports array of structures.
  • Used in file handling and dynamic data structures.
  • Padding affects memory size.

20. Conclusion

Structures are one of the most powerful features in C programming. They allow programmers to model real-world entities efficiently by grouping related data. Structures improve readability, maintainability, and modularity of programs. They are essential for building complex applications such as databases, operating systems, and data structures like linked lists and trees.


Comments

Popular Posts