C Lesson 26 – Structure | Dataplexa

Structures in C

Until now, you have worked with individual variables and arrays.

But real-world data is not isolated. It comes as a group of related values.

This is exactly why structures exist in C.


Why Do We Need Structures?

Imagine storing student information:

  • Roll number
  • Name
  • Marks

Using separate variables quickly becomes messy.

Structures allow you to group related data under one name.


What Is a Structure?

A structure is a user-defined data type that holds multiple variables of different types.

All members are stored together in memory.


Defining a Structure


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

This creates a blueprint. No memory is allocated yet.


Creating Structure Variables


struct Student s1;

Now memory is allocated for all members.


Accessing Structure Members

Use the dot operator (.):


s1.roll = 101;
strcpy(s1.name, "Rahul");
s1.marks = 85.5;

Complete Example


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

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

int main() {
    struct Student s1;

    s1.roll = 1;
    strcpy(s1.name, "Anita");
    s1.marks = 92.5;

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

    return 0;
}

Memory Layout of a Structure

All members are stored sequentially in memory.

The total size may include padding for alignment.

You can check size using:


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

Real-World Analogy

Think of a structure like an ID card:

  • Name
  • ID number
  • Department

All information belongs to one person and is kept together.


Why Structures Are Important

  • Organize complex data
  • Improve code readability
  • Foundation for files, databases, and OS structures

Mini Practice

  • Create a structure for a book
  • Members: title, author, price
  • Store and display values

Quick Quiz

Q1. What is a structure?

A user-defined data type that groups related variables.

Q2. Does defining a structure allocate memory?

No.

Q3. Which operator is used to access structure members?

Dot operator (.).

Q4. Can a structure contain different data types?

Yes.

Q5. Are structures important in real programs?

Yes, they are fundamental.