Data Structure: Structures in C Programming

What is a Structure?

A structure in C is a user-defined data type that allows grouping different data types under a single name. It helps in organizing complex data efficiently.

  • In primitive types, like int, float, char, you can store only one value at a time.
  • In arrays, you can store multiple values but all of the same type.
  • A structure solves this limitation: it can store multiple values of different types together.

Why Use Structures?

  • Stores related data (e.g., student records, employee details etc.).
  • Combines different data types (int, float, char, etc.).
  • Improves code readability and reusability.

Example 1: Real-World Analogy

Think of a student record. A student has:

  • An ID (integer type)
  • A name (string type)
  • Marks (float type)

These different data types are part of one student’s record. A structure groups these into a single unit.

Structure Syntax and Components
  • struct is the keyword.
  • structure_name is the name of the new user-defined type.
  • Members can be of different types.
  • Syntax:
struct structure_name {
    data_type Member1;
    data_type Member2;
    ... // More members may be included
};

Example 2:

struct Student {
    char name[50];
    int roll_no;
    float marks;
};
  • struct Student defines a new data type.
  • name, roll_no, and marks are members.
Declaring Structure Variables

Method 1: During Definition

struct Student {
    char name[50];
    int roll_no;
    float marks;
} s1, s2;  // Declares variables s1 and s2

Method 2: After Definition

struct Student s1, s2;
Accessing Structure Members

Using the Dot (.) Operator

strcpy(s1.name, "Alice");
s1.roll_no = 111;
s1.marks = 85.5;

Example 3:

#include <stdio.h>
#include <string.h>

struct Student {                      // struct Student is a user-defined type
    int id;
    char name[50];
    float marks;
};

int main() {
    struct Student s1;               // s1 is a structure variable.

    s1.id = 111;                     // Members are accessed using dot operator (.)
    strcpy(s1.name, "Alice");       // Members are accessed using dot operator (.)
    s1.marks = 85.5;                // Members are accessed using dot operator (.)

    printf("ID: %d\n", s1.id);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}
Array of Structures
  • We can create an array of structures to store data for multiple entities.
struct Student students[100];

Above command help us to manage data for 100 students, each with their own set of attributes.

Example 4:

#include <stdio.h>
#include <string.h>

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

int main() {
    struct Student report[3] = {
        {"MrX", 1, 94.50},
        {"MsY", 2, 90.25},
        {"MrZ", 3, 82.80}
    };
    
    for (int i = 0; i < 3; i++) {
        printf("Student %d: %s, %d, %.2f\n",
               i+1, report[i].name, report[i].roll_no, report[i].marks);
    }

    return 0;
}

Output:

Student 1:   MrX   1   94.50
Student 2:   MsY   2   90.25
Student 3:   MrZ   3   82.80

Nested Structures in C Programming

  • In C programming, a nested structure refers to a structure defined inside another structure. It enables us to group related information in a more hierarchical and organized manner.
Why Use Nested Structures?
  • To logically group data that belongs to a single entity.
  • Improves modularity and readability of the program.
  • Useful in complex data representations (e.g., student record with name, address, scores, etc.)

Syntax:

struct Inner {
    int x;
    float y;
};

struct Outer {
    int id;
    struct Inner data;    // Nested structure
};

Example 5: Nested Structure

#include <stdio.h>

struct Address {
    char city[20];
    int pin;
};

struct Student {
    char name[20];
    int roll;
    struct Address addr;  // Nested structure
};

int main() {
    struct Student s1 = {"Rahul", 101, {"Kolkata", 700001}};

    printf("Name: %s\n", s1.name);
    printf("Roll: %d\n", s1.roll);
    printf("City: %s\n", s1.addr.city);
    printf("PIN: %d\n", s1.addr.pin);

    return 0;
}
  • Accessing Nested Members

Use the dot (.) operator multiple times:

s1.addr.city    // Access city inside Address inside Student
s1.addr.pin
  • Initializing Nested Structures
struct Student s2 = {
    "Alex",
    102,
    {" Macedonia_Gostivar", 1230}
};

Example 6: Nested Structure with Input from User

#include <stdio.h>

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

struct Employee {
    int id;
    char name[30];
    struct Date doj;  // Date of Joining
};

int main() {
    struct Employee e;

    printf("Enter employee ID: ");
    scanf("%d", &e.id);

    printf("Enter employee name: ");
    scanf("%s", e.name);

    printf("Enter date of joining (dd mm yyyy): ");
    scanf("%d %d %d", &e.doj.day, &e.doj.month, &e.doj.year);

    printf("\n--- Employee Info ---\n");
    printf("ID: %d\n", e.id);
    printf("Name: %s\n", e.name);
    printf("Date of Joining: %02d-%02d-%04d\n", e.doj.day, e.doj.month, e.doj.year);

    return 0;
}

Pointers to Structures in C Programming

  • In C, pointers to structures allow us to dynamically manipulate structure data, pass large structures efficiently to functions, and work effectively with dynamic memory.
  • A structure pointer is a pointer variable that stores the address of a structure variable.
struct Student {
    int roll;
    char name[20];
};

struct Student s1;
struct Student *ptr;

ptr = &s1;  // ptr stores the address of s1
Why Use Pointers to Structures?
  • Efficient memory usage.
  • Dynamic memory allocation.
  • Easier to pass structures to functions.
  • Useful in linked lists, trees, and other data structures.

Accessing Members Using Structure Pointers

We can access structure members using:

  • (*ptr).member
  • Ptr->member
  • Syntax
ptr->roll = 101;
strcpy(ptr->name, "RohitX");

Example:

#include <stdio.h>
#include <string.h>

struct Student {
    int roll;
    char name[20];
};

int main() {
    struct Student s1;
    struct Student *ptr;

    ptr = &s1;

    ptr->roll = 101;
    strcpy(ptr->name, "Alicent");

    printf("Roll: %d\n", ptr->roll);
    printf("Name: %s\n", ptr->name);

    return 0;
}

Pointer to Array of Structures in C Programming

  1. A pointer to an array of structures is a pointer that can access multiple structure variables stored in contiguous memory locations.
  2. This concept combines:
    • Pointers
    • Arrays
    • Structures
  3. It’s commonly used when:
    • We want to dynamically allocate memory for structures.
    • We want to pass an array of structures to a function.
    • We need efficient manipulation of structure data.

Example:

struct Student {
    int roll;
    float marks;
};

int main() {
    struct Student arr[3] = {{1, 85.5}, {2, 90.0}, {3, 78.0}};
    struct Student *ptr = arr;  // pointer to first element

    for (int i = 0; i < 3; i++) {
        printf("Roll: %d, Marks: %.2f\n", (ptr+i)->roll, (ptr+i)->marks);
    }

    return 0;
}

Passing Structures to Functions in C Programming

  • In real-world programs, structures often hold data about entities like students, employees, products, etc. To modularize code, we pass these structures to functions for operations like:
    1. Displaying data
    2. Modifying records
    3. Calculating results
  • There are two main ways to pass structures to functions:

MethodDescriptionCopy or ReferenceEfficient?
Pass by ValueA copy of the
structure is passed
CopyLess efficient (❌)
Pass by ReferenceAddress (pointer) of
structure is passed
ReferenceMore efficient (✅)

 

Leave a Comment

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

Scroll to Top