🧑‍💻 Structures in C Programming – Complete Beginner to Advanced Guide with Fully Commented Programs


🚀 Introduction

In C programming, arrays allow us to store multiple values of the same data type.

But what if we want to store:

  • Student name (string)

  • Roll number (int)

  • Marks (float)

All together in a single unit?

👉 That’s where Structures come into the picture.

A structure allows us to group different data types under one name.


📌 Real-World Use of Structures

Structures are used in:

  • Student Record Systems

  • Employee Databases

  • Banking Applications

  • Inventory Management Systems

  • Operating Systems

  • File Handling

If you understand structures properly, you are ready for advanced C programming.


📌 1️⃣ What is a Structure in C?

A structure is a user-defined data type that allows grouping variables of different data types under one name.

Unlike arrays (same data type), structures can store different types together.


📌 2️⃣ Syntax of Structure

#include <stdio.h> // Include standard input-output header file

struct Student // Define structure named Student
{
int roll; // Integer variable to store roll number
char name[50]; // Character array to store name
float marks; // Floating-point variable to store marks
};
// Semicolon is mandatory after structure

📌 3️⃣ Program to Use Structure (Fully Commented)

💻 Program: Store and Display Student Details

#include <stdio.h> // Include standard input-output library

struct Student // Define structure named Student
{
int roll; // Roll number of student
char name[50]; // Name of student
float marks; // Marks of student
};

int main() // Main function starts
{
struct Student s1; // Declare structure variable

printf("Enter Roll: ");
scanf("%d", &s1.roll); // Read roll number (address required)

printf("Enter Name: ");
scanf("%s", s1.name); // Read name (array name acts as address)

printf("Enter Marks: ");
scanf("%f", &s1.marks); // Read marks

printf("\n--- Student Details ---\n");
printf("Roll: %d\n", s1.roll); // Print roll number
printf("Name: %s\n", s1.name); // Print name
printf("Marks: %.2f\n", s1.marks); // Print marks with 2 decimal precision

return 0; // Return 0 to operating system
}

🧠 Time Complexity: O(1) – Constant time
Edge Case: scanf("%s") does not read spaces. Use fgets() for full names.
Common Mistake: Forgetting semicolon after structure definition.


📌 4️⃣ Array of Structures

Used when storing multiple students.

#include <stdio.h> // Include standard I/O library

struct Student // Define structure
{
int roll; // Roll number
char name[50]; // Name
float marks; // Marks
};

int main() // Main function
{
struct Student s[2]; // Declare array of 2 structures
int i; // Loop variable

for(i = 0; i < 2; i++) // Loop for input
{
printf("\nEnter details of Student %d\n", i+1);

printf("Roll: ");
scanf("%d", &s[i].roll); // Access roll of ith student

printf("Name: ");
scanf("%s", s[i].name); // Access name of ith student

printf("Marks: ");
scanf("%f", &s[i].marks); // Access marks of ith student
}

printf("\n--- Student Details ---\n");

for(i = 0; i < 2; i++) // Loop for output
{
printf("\nStudent %d\n", i+1);
printf("Roll: %d\n", s[i].roll);
printf("Name: %s\n", s[i].name);
printf("Marks: %.2f\n", s[i].marks);
}

return 0; // Return statement
}

🧠 Time Complexity: O(n)
Common Mistake: Writing s.roll instead of s[i].roll.


📌 5️⃣ Pointer to Structure

#include <stdio.h> // Include standard I/O library

struct Student // Define structure
{
int roll; // Roll number
float marks; // Marks
};

int main() // Main function
{
struct Student s1 = {101, 95.5}; // Initialize structure
struct Student *ptr; // Declare pointer to structure

ptr = &s1; // Store address of structure in pointer

printf("Roll: %d\n", ptr->roll); // Access roll using arrow operator
printf("Marks: %.2f\n", ptr->marks);// Access marks using arrow operator

return 0; // Return statement
}

🧠 Use -> operator when using pointer.
❌ Do not use dot operator with pointer.


📌 6️⃣ Nested Structure

#include <stdio.h> // Include standard I/O library

struct Address // Define Address structure
{
char city[20]; // City name
int pincode; // Pincode
};

struct Student // Define Student structure
{
int roll; // Roll number
struct Address addr; // Nested structure
};

int main() // Main function
{
struct Student s1 = {101, {"Rajkot", 360001}}; // Initialize nested structure

printf("Roll: %d\n", s1.roll); // Print roll
printf("City: %s\n", s1.addr.city); // Access nested member city
printf("Pincode: %d\n", s1.addr.pincode); // Access nested pincode

return 0; // Return statement
}

📌 7️⃣ Structure vs Array

Feature Array Structure
Definition Collection of elements of same data type Collection of elements of different data types
Data Type All elements must be same type Members can be different types
Memory Allocation Stored in contiguous memory locations Memory allocated for each member
Access Method Using index (arr[0]) Using dot operator (s.name)
Purpose Stores similar type of data Stores related but different data
Keyword Used No special keyword required Uses struct keyword
Example Declaration int marks[5]; struct Student { int roll; char name[20]; };
Example Usage marks[0] = 90; student.roll = 1;
Size Calculation Number of elements × size of data type Sum of sizes of all members

📌 8️⃣ Important Interview Questions (DETAILED ANSWERS)



🔹 1️⃣ What is Structure Padding?

✅ Explanation

Structure padding is extra memory added by the compiler between structure members to ensure proper memory alignment.

Why?

  • CPU accesses memory faster when data is aligned properly.

  • Each data type has alignment rules.

  • Compiler may insert unused bytes (padding) between members.

Example:

  • char → 1 byte

  • int → 4 bytes

  • Compiler aligns int on 4-byte boundary

So padding is added after char.


💻 Fully Commented Program

#include <stdio.h> // Include standard input-output library

struct Example // Define structure named Example
{
char a; // 1 byte character variable
int b; // 4 bytes integer (needs 4-byte alignment)
};

int main() // Main function starts
{
printf("Size: %lu\n", sizeof(struct Example));
// sizeof calculates total size of structure including padding

return 0; // Return 0 means successful execution
}

🧠 Memory Layout (Important for Interviews)

char a → 1 byte
padding → 3 bytes (added by compiler)
int b → 4 bytes
-------------------------
Total size → 8 bytes

📌 Without padding → 5 bytes
📌 With padding → 8 bytes

Padding improves performance by proper memory alignment.


🔹 2️⃣ Difference Between Structure and Union

✅ Explanation

Structure

  • Each member gets separate memory.

  • All members can store values at same time.

  • Size = Sum of all members (including padding).

Union

  • All members share same memory location.

  • Only one member can store value at a time.

  • Size = Size of largest member.


💻 Fully Commented Program

#include <stdio.h> // Include standard I/O library

struct TestS // Define structure
{
int x; // 4 bytes integer
float y; // 4 bytes float
};

union TestU // Define union
{
int x; // Shares same memory
float y; // Shares same memory
};

int main() // Main function
{
printf("Structure Size: %lu\n", sizeof(struct TestS));
// Prints total size of structure (likely 8)

printf("Union Size: %lu\n", sizeof(union TestU));
// Prints size of union (largest member, likely 4)

return 0; // Successful execution
}

Feature Structure Union
Definition Collection of different data types stored separately Collection of different data types sharing same memory
Memory Allocation Each member gets separate memory space All members share the same memory space
Usage of Members All members can store values at the same time Only one member can store value at a time
Size Sum of sizes of all members (including padding) Size of the largest member
Keyword Used struct union
Memory Efficiency Less memory efficient More memory efficient
Data Safety Data remains safe for all members Changing one member affects others
Access Method Using dot operator (s.name) Using dot operator (u.name)
Example Declaration struct Student { int roll; float marks; }; union Data { int i; float f; };
Best Used When Need to store complete record of data Need to save memory and store one value at a time

🔹 3️⃣ What is typedef with Structure?

✅ Explanation

typedef creates an alias (alternative name) for a data type.

Normally we write:

struct Student s1;

With typedef, we can write:

Student s1;

This makes code cleaner and professional.


💻 Fully Commented Program

#include <stdio.h> // Include standard I/O library

typedef struct // Create alias for structure
{
int roll; // Roll number variable
float marks; // Marks variable
} Student; // Student becomes alias name

int main() // Main function
{
Student s1; // Declare structure using alias

s1.roll = 101; // Assign value to roll
s1.marks = 89.5; // Assign value to marks

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

return 0; // Return statement
}

✅ Advantage → Cleaner and easier to read code.


🔹 4️⃣ Can Structure Contain Pointer?

✅ Explanation

Yes, a structure can contain pointer members.

This is very important for:

  • Linked Lists

  • Trees

  • Dynamic Memory Allocation

  • Graphs

Pointers inside structure store addresses of variables or other structures.


💻 Fully Commented Program

#include <stdio.h> // Include standard I/O library

struct Student // Define structure
{
int roll; // Integer variable
int *ptr; // Pointer member (stores address)
};

int main() // Main function
{
int x = 50; // Declare integer variable

struct Student s1; // Declare structure variable

s1.roll = 101; // Assign roll number
s1.ptr = &x; // Store address of x into pointer

printf("Value of x: %d\n", *s1.ptr);
// Dereference pointer to access value of x

return 0; // Return statement
}

🔹 5️⃣ Can Structure Be Passed to Function?

✅ Explanation

Yes, structure can be passed in two ways:

Feature Passing by Value Passing by Reference
Definition Entire structure is copied to function Address of structure is passed to function
Memory Usage Creates a duplicate copy (more memory used) No duplicate copy (less memory used)
Speed Slower for large structures Faster and more efficient
Effect on Original Data Changes do NOT affect original structure Changes affect original structure
Safety Safer (original data protected) Risky if function modifies data unintentionally
Data Sharing Works on independent copy Works on same memory location
Use of Pointer No pointer required Pointer required
Syntax Example void func(struct Student s) void func(struct Student *s)
Access Inside Function Using dot operator (s.roll) Using arrow operator (s->roll)
Best Used When Structure size is small Structure size is large

💻 Passing Structure by Value (Fully Commented)

#include <stdio.h> // Include standard I/O library

struct Student // Define structure
{
int roll; // Roll number
};

void display(struct Student s) // Structure passed by value (copy created)
{
printf("%d\n", s.roll); // Access copied data
}

int main() // Main function
{
struct Student s1 = {101}; // Initialize structure

display(s1); // Pass structure (copy sent)

return 0; // Return statement
}

💻 Passing Structure by Reference (Fully Commented)

#include <stdio.h> // Include standard I/O library

struct Student // Define structure
{
int roll; // Roll number
};

void display(struct Student *s) // Pointer parameter (address received)
{
printf("%d\n", s->roll); // Access using arrow operator
}

int main() // Main function
{
struct Student s1 = {101}; // Initialize structure

display(&s1); // Pass address of structure

return 0; // Return statement
}

🎯 Final Interview Tip

If interviewer asks:

Which method is better?

Answer:

👉 Passing by reference is better for large structures because it avoids copying entire structure and improves performance.


🏁 Final Conclusion

Structures are the foundation of advanced C concepts such as:

  • Linked Lists

  • Trees

  • File Handling

  • Dynamic Memory Allocation

After mastering:

Arrays
Pointers
Functions
Structures

You are now ready for real-world C development 🚀


📌 Keep Learning. Keep Coding. Keep Growing.

✨ Written by Krishna Popat
🌱 Founder, Learning Growth Hub

Comments

Popular posts from this blog

🌟 The Honest Journey of a Student: Learning, Failing, and Growing

“C Programming for Beginners: Master Variables, Data Types, and Memory (Bits Explained)”