View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Structures in C Made Easy: Learn with Real Examples

Updated on 30/05/20253,183 Views

C is often hailed as the "mother of all programming languages" for a reason—it's fast, close to hardware, and gives you complete control over memory. But with great power comes the need for better data management. That’s where Structures in C come into play. When a program grows beyond basic variables and arrays, structures help group multiple data types under one name, allowing you to model complex real-world entities with elegance and efficiency.

Whether you’re building a student database, managing an employee payroll system, or designing a basic game, you'll find structures indispensable. They allow you to pack related data together, reducing clutter and improving code readability. In this article, we’ll take a deep dive into Structures in C—how to declare them, use them with arrays and functions, avoid common mistakes, and much more.

Explore Online Software Development Courses from top universities.

What Are Structures in C?

In C programming, a structure is a user-defined data type that allows you to combine data items of different types under a single name. Think of it as a way to bundle related variables together, so you don’t have to manage them separately. Imagine managing information about a student. You need a roll number (int), name (string), and marks (float). You could declare three separate variables:

int roll;

char name[50];

float marks;

But if you have hundreds of students, this quickly turns into a nightmare. Here’s where a structure saves the day—it lets you define a Student type with all the needed attributes.

This declaration doesn’t allocate memory; it just defines a template or blueprint. You'll need to declare variables using this structure to use it in your program.

If you’re ready to grow your skills, check out these programs:

How to Declare and Define a Structure in C?

Declaring and defining a structure in C involves two simple steps:

Step 1: Define the Structure

Use the struct keyword, followed by the structure name and the members enclosed in braces {}.

Syntax:

struct StructureName {
    dataType member1;
    dataType member2;
    // more members...
};

Example:

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

This code defines a structure named Student with three members: roll, name, and marks.

Also Read- Fiboancci Series in C using Recursion 

Step 2: Declare Structure Variables

After defining the structure, you can create variables (objects) of that structure type.

struct Student s1, s2;

Here, s1 and s2 are two variables of type struct Student.

Optional: Declare and Define in One Statement

You can also declare a structure variable while defining the structure:

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

Important Note

Defining the structure does not allocate memory for its variables. Memory is allocated only when you declare variables of that structure type.

Why Do We Use Structures in C?

Structures in C serve one main purpose: to group related data together. C is a powerful low-level language, but it doesn't come with built-in support for objects like modern OOP languages do. That’s where structures shine: they help you organize and manage complex, real-world data using a simple and structured approach.

Let’s say you’re building a system to manage hospital patients. Each patient has a name, age, ID number, and health status. Using structures, you can represent all of this with a single custom data type called Patient, instead of declaring four different variables for each one. This improves code organization, readability, and reusability.

You can also Explore: C Program for String Palindrome

Benefits of Using Structures

  1. Logical Grouping Structures allow you to keep related data bundled together under one name, which simplifies management and reduces errors.
  2. Improved Code Clarity When you use structures, your code reads more like a sentence describing a real-world concept—making it easier to understand and debug.
  3. Function Argument Efficiency You can pass an entire structure to a function instead of multiple individual variables, streamlining function calls.
  4. Scalability Need to store records of hundreds of employees, books, or students? Structures paired with arrays or pointers make this scalable and maintainable.

Example: Without Structure vs With Structure

Without Structure:

int roll1 = 101;
char name1[50] = "Aniket";
float marks1 = 88.5;

With Structure:

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

struct Student s1 = {101, "Aniket", 88.5};

Output: Both snippets store the same data, but the second one is more intuitive and organized.

Explanation: The structured version reduces the chance of mismatched variables and enhances clarity. Plus, it becomes easier to manage multiple records.

Also Read: Matrix Multiplication in C

How to Access Members of a Structure?

Once you declare a structure variable, you can access its individual members using the dot (.) operator.

Syntax:

variableName.memberName

Example:

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

struct Student s1;

s1.roll = 101;
strcpy(s1.name, "Rajat");  // Copying string into name
s1.marks = 89.5;

Explanation:

  • s1.roll = 101; assigns the roll number.
  • strcpy(s1.name, "Rajat"); copies the string "Rajat" into the name array. (Strings need to be copied since arrays can’t be assigned directly.)
  • s1.marks = 89.5; assigns marks.

Output Example:

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

Output:

Roll: 101

Name: Rajat

Marks: 89.50

Must Check: Decimal to Binary in C

How to Use Arrays Within Structures?

Structures in C can hold arrays as members. This is especially useful when you want to store multiple related values inside one structure member.Consider storing the names of multiple subjects a student studies. Instead of creating separate variables for each subject, you can define an array inside the structure to hold all subject names.

Example: Student with Subject Marks Array

struct Student {
    int roll;
    char name[50];
    float marks[5];  // Marks for 5 subjects
};

Using the Structure:

struct Student s1;

s1.roll = 102;
strcpy(s1.name, "Pooja");

// Assign marks for 5 subjects
s1.marks[0] = 85.5;
s1.marks[1] = 90.0;
s1.marks[2] = 78.5;
s1.marks[3] = 88.0;
s1.marks[4] = 92.5;

Output Code:

printf("Marks of %s:\n", s1.name);
for (int i = 0; i < 5; i++) {
    printf("Subject %d: %.2f\n", i + 1, s1.marks[i]);
}

Output:

Marks of Pooja:

Subject 1: 85.50

Subject 2: 90.00

Subject 3: 78.50

Subject 4: 88.00

Subject 5: 92.50

Explanation:

  • The marks array inside the structure allows storing multiple related values.
  • Access array elements with the dot (.) operator followed by array indexing.

Must Check- Pseudo Code in C

How to Use Structures with Functions?

Passing structures to functions is a common practice that improves modularity and code clarity. You can pass a whole structure as an argument to a function, allowing the function to access or modify the grouped data.

Two Ways to Pass Structures to Functions

  1. Pass by Value: The function receives a copy of the structure. Changes inside the function do not affect the original structure.
  2. Pass by Reference (Using Pointers): The function receives a pointer to the structure. Changes inside the function will modify the original structure.

Example: Pass Structure by Value

#include <stdio.h>
struct Student {
    int roll;
    char name[50];
    float marks;
};

void printStudent(struct Student s) {
    printf("Roll: %d\n", s.roll);
    printf("Name: %s\n", s.name);
    printf("Marks: %.2f\n", s.marks);
}

int main() {
    struct Student s1 = {101, "Anjali", 92.5};
    printStudent(s1);
    return 0;
}

Output:

Roll: 101

Name: Anjali

Marks: 92.50

Example: Pass Structure by Reference (Pointer)

#include <stdio.h>
struct Student {
    int roll;
    char name[50];
    float marks;
};

void updateMarks(struct Student *s, float newMarks) {
    s->marks = newMarks;  // Using -> operator for pointer
}

int main() {
    struct Student s1 = {102, "Rajat", 88.0};
    updateMarks(&s1, 95.0);
    printf("Updated Marks: %.2f\n", s1.marks);
    return 0;
}

Output:

Updated Marks: 95.00

Explanation:

  • When passing by value, the function works on a copy, so original data stays unchanged.
  • When passing by reference, the function can modify the original structure using pointers (-> operator).

Must Check - Double in C

Real-Life Example of Structures in C

Let’s create a practical program that uses a structure to store and display information about multiple students.

Example:

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

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

int main() {
    struct Student s1, s2;

    // Student 1 details
    s1.roll = 101;
    strcpy(s1.name, "Swastik");
    s1.marks = 87.5;

    // Student 2 details
    s2.roll = 102;
    strcpy(s2.name, "Arushi");
    s2.marks = 91.0;

    // Display student details
    printf("Student 1:\nRoll: %d\nName: %s\nMarks: %.2f\n\n", s1.roll, s1.name, s1.marks);
    printf("Student 2:\nRoll: %d\nName: %s\nMarks: %.2f\n", s2.roll, s2.name, s2.marks);

    return 0;
}

Output:

Student 1:

Roll: 101

Name: Swastik

Marks: 87.50


Student 2:

Roll: 102

Name: Arushi

Marks: 91.00

Explanation:

  • We declared two variables s1 and s2 of type struct Student.
  • Used strcpy() to assign names because arrays cannot be assigned directly.
  • Printed each student’s details using the dot (.) operator.
  • This example clearly shows how structures can group different data types logically.

Also Read - Square Root in C

Tips and Tricks to Master Structures in C

Mastering structures doesn’t just mean knowing syntax—it’s about using them smartly to write clean, efficient, and logical code. Here are some actionable tips and tricks to help you level up:

  • Use typedef for Clean Code

Writing struct Student repeatedly can get annoying. Use typedef to simplify:

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

Student s1; // cleaner than struct Student s1;

Tip: It improves readability, especially in large codebases.

  • Initialize Members During Declaration

You can assign values directly at declaration:

struct Student s1 = {101, "Anjali", 92.5};

Why it helps: Saves time and prevents uninitialized (garbage) values.

  • Use strcpy() for Strings Inside Structures

You cannot assign strings directly to character arrays inside structures:

// Incorrect:
s1.name = "Pooja";  // Not allowed
// Correct:
strcpy(s1.name, "Pooja");
  • Prefer Passing by Reference for Efficiency

When dealing with large structures, pass by reference using pointers:

void update(Student *s) {
    s->marks += 5; // adds grace marks
}

Why? Passing by value copies all members, which wastes memory and slows down performance.

Must Check - Static Function in C

  • Combine Structures with Arrays for Real Projects

Want to store multiple students?

Student class[50];  // array of 50 students

Loop through them to store or display data — ideal for real-world school/college apps.

  • Use Nested Structures Smartly

Group related data types using nested structures:

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

struct Student {
    int roll;
    char name[50];
    struct Address addr;
};

Use case: Keeps your main structure clean and modular.

  • Align Structure Members for Better Memory Usage

Place larger data types first:

struct Optimized {
    int id;
    char name[50];
    char gender;
};

Why it matters: Helps reduce memory padding and saves space.

  • Bonus Tip: Use Debug Prints While Learning

It’s easy to lose track of data when learning. Add printf() statements after key changes to monitor your structure's behavior in real-time.

Also Read - Identifiers in C

Common Mistakes to Avoid While Using Structures

Even seasoned C programmers can fumble with structures if they ignore certain details. Avoiding these ensures cleaner, safer, and more efficient code.

1. Direct string assignment (invalid): s1.name = "Raj"; // wrong

2. Forgetting #include <string.h> when using strcpy.

3. Using dot instead of arrow with pointers.

4. Passing large structures by value instead of reference.

5. Using uninitialized structure variables.

6. Misjudging structure size due to padding.

7. Improper nested structure access.

8. Not using typedef where useful.

Also Read - Nested For Loop in C

Conclusion: Are Structures Still Relevant in Modern C?

Absolutely. Even with the evolution of languages and the rise of object-oriented programming, structures in C continue to hold their ground. In fact, they serve as the backbone for many advanced programming concepts—like linked lists, file handling, and even embedded systems.

Structures are not just a feature; they’re a foundational tool in C that teaches modularity, logical grouping, and memory-efficient design. Whether you're building a student database, modeling bank accounts, or writing a compiler, structures help bring order to chaos.

So the next time someone says, "Structures are outdated," just smile and remind them that even the most modern tech stacks still rely on this good old workhorse behind the scenes. Learn them, practice them, and use them like a seasoned programmer—because in the world of C, structures are here to stay.

FAQS

1. What is the use of structures in C?

Structures group related variables of different data types, improving data organization and making programs easier to manage, especially in scenarios like student databases, banking systems, and file handling.

2. Can we assign one structure to another in C?

Yes, direct structure-to-structure assignment is allowed in C, provided both variables belong to the same structure type. All members are copied in one go.

3. What is the size of a structure in C?

The size varies depending on the member data types and alignment rules. Padding may increase the size beyond the simple sum of its members. Use sizeof() to get accurate size.

4. Can we use functions inside structures in C?

No, C does not support defining functions inside structures. However, you can use function pointers or pass structures to functions to achieve modular behavior.

5. Can we declare an array inside a structure in C?

Yes, you can include arrays inside a structure to store multiple elements, like char name[50];. It’s commonly used in real-world programs for handling strings or marks.

6. How can we pass a structure to a function?

You can pass a structure by value (copy of data) or by reference using pointers. Passing by reference saves memory and allows direct modification of the original data.

7. Is it necessary to use typedef with structures?

Not mandatory, but highly recommended. It reduces syntax repetition, improves readability, and simplifies structure variable declarations in large-scale applications.

8. Can structures contain pointers?

Yes, structures can have pointer members like char *name;. They're helpful for dynamic memory allocation, but you must handle memory management properly to avoid leaks.

9. What is structure padding in C?

Padding adds extra memory between members to align data efficiently for the CPU. This can lead to increased memory usage, so arrange structure members from largest to smallest when possible.

10. How is a structure different from a union in C?

Structures store each member separately, while unions share the same memory space among all members. Use structures when storing all values; use unions when memory efficiency is critical.

11. Can we nest one structure inside another?

Yes, nested structures are allowed and useful for organizing complex data. For example, a Student structure can contain an Address structure for modular design.

12. How do we access structure members using pointers?

Use the arrow (->) operator for pointers. For example, ptr->name accesses the name member of a structure pointer ptr. The dot operator only works with structure variables.

13. Are structures passed by value or by reference in C?

By default, structures are passed by value, meaning a copy is made. To modify the original or save memory, pass the structure by reference using pointers.

14. Can a structure have flexible array members?

Yes, C allows flexible array members as the last element in a structure using int arr[];. This is used for scenarios where the array size is determined at runtime.

15. When should I prefer structures over arrays?

Use structures when you need to store data of different types together (e.g., name, roll, and marks). Arrays are ideal for storing similar data types like a list of marks.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.