13. Structures & Unions
So far, you have worked with individual values such as int, float, char, arrays and pointers.
But real programs often need to represent an entity containing different kinds of information.
For example, a student may have:
- Student ID →
int - Name → character array
- Marks →
float - Age →
int
A structure lets us group these related members into one object.
A union also groups different members, but its members share the same storage.
13.1 What Is a Structure?
A structure is a user-defined type that groups related data items, called members, under one object.
The members can have different data types.
struct Student { int id; char name[50]; float marks; }; This defines a structure type named struct Student.
It describes what a student object will contain.
Student object by itself. It defines the type. 13.2 Why Are Structures Needed?
Suppose you want to store information about three students. Without structures, you might create separate variables:
int id1, id2, id3; char name1[50]; char name2[50]; char name3[50]; float marks1, marks2, marks3; This becomes difficult to organize.
With structures:
struct Student students[3]; Each array element represents one complete student record.
Without Structure
Related information is scattered across separate variables.
With Structure
Related information is grouped into one meaningful object.
13.3 Structure Syntax
struct StructureName { data_type member1; data_type member2; data_type member3; }; Example:
struct Employee { int id; char name[40]; float salary; }; The keyword struct introduces a structure specification.
The name after struct is called the tag.
struct
Keyword used to define or refer to a structure.
Employee
Structure tag identifying this structure type.
Members
Variables stored inside each structure object.
13.4 Creating Structure Variables
After defining the structure type, create objects using:
struct Student s1; struct Student s2; Now s1 and s2 are two separate structure objects.
struct Student { int id; float marks; }; int main(void) { struct Student s1; s1.id = 101; s1.marks = 85.5f; return 0; } Structure Object
struct Student s1 ┌───────────────────────────────┐ │ id │ 101 │ ├──────────┼────────────────────┤ │ marks │ 85.5 │ └───────────────────────────────┘ s1 is one complete Student object. Each member has its own storage.
13.5 Accessing Structure Members with .
The dot operator . is used to access a member of a structure object.
s1.id s1.marks Example:
#include <stdio.h> struct Student { int id; float marks; }; int main(void) { struct Student s; s.id = 101; s.marks = 92.5f; printf("ID = %d\n", s.id); printf("Marks = %.2f\n", s.marks); return 0; } structureObject.member is the normal syntax for accessing a structure member. 13.6 Initializing Structures
A structure object can be initialized when it is created.
struct Student s = {101, 85.5f}; The values are assigned to members in declaration order.
struct Student { int id; float marks; }; struct Student s = {101, 85.5f}; Therefore:
s.id → 101 s.marks → 85.5 Before C99 style
Positional initialization follows member order.
C99 Designated Initialization
struct Student s = { .marks = 85.5f, .id = 101 }; 13.7 Updating Structure Members
Structure members can be changed just like ordinary variables.
struct Student s = {101, 80.0f}; s.marks = 90.0f; After the assignment:
s.id = 101 s.marks = 90.0 The complete structure object remains the same object; only one member is changed.
13.8 Program Tracing: Structure Members
struct Student { int id; int marks; }; int main(void) { struct Student s; s.id = 101; s.marks = 85; s.marks = s.marks + 5; return 0; } Step 1 struct Student s; ┌──────────────────────┐ │ id │ ? │ ├───────┼──────────────┤ │ marks │ ? │ └──────────────────────┘ Step 2 s.id = 101; ┌──────────────────────┐ │ id │ 101 │ ├───────┼──────────────┤ │ marks │ ? │ └──────────────────────┘ Step 3 s.marks = 85; ┌──────────────────────┐ │ id │ 101 │ ├───────┼──────────────┤ │ marks │ 85 │ └──────────────────────┘ Step 4 s.marks = s.marks + 5; ┌──────────────────────┐ │ id │ 101 │ ├───────┼──────────────┤ │ marks │ 90 │ └──────────────────────┘
13.9 Understanding the Structure Tag
struct Student { int id; float marks; }; Here Student is the structure tag.
You normally write the type as:
struct Student not simply:
Student Student as a standalone type name from struct Student. The typedef mechanism can create such an alias, which is covered later. 13.10 Structure Definition vs Structure Variable
Type definition:
struct Book { int pages; float price; }; Object declaration:
struct Book b1; The first describes the type. The second creates an object.
Both can also be written together:
struct Book { int pages; float price; } b1, b2; b1 and b2 are created by the declarators following the closing brace. 13.11 Multiple Structure Variables
struct Point { int x; int y; }; int main(void) { struct Point p1 = {10, 20}; struct Point p2 = {30, 40}; printf("%d %d\n", p1.x, p1.y); printf("%d %d\n", p2.x, p2.y); return 0; } Each object has its own members.
p1 ┌───────────────┐ │ x = 10 │ │ y = 20 │ └───────────────┘ p2 ┌───────────────┐ │ x = 30 │ │ y = 40 │ └───────────────┘ p1 and p2 are separate objects.
13.12 Structure Assignment
Two structure objects of compatible structure type can be assigned to each other.
struct Student { int id; float marks; }; int main(void) { struct Student s1 = {101, 85.0f}; struct Student s2; s2 = s1; printf("%d %.2f\n", s2.id, s2.marks); return 0; } The assignment copies the value of the structure object, including array members that are part of the structure.
13.13 Can We Compare Structures with ==?
C does not provide direct == or != operators for comparing complete structure objects.
Instead, compare the relevant members.
if (s1.id == s2.id && s1.marks == s2.marks) { printf("Same selected values"); } if (s1 == s2) for ordinary C structure objects. 13.14 Nested Structures
A structure can contain another structure as a member.
struct Date { int day; int month; int year; }; struct Student { int id; struct Date dob; }; Access nested members using multiple dot operators:
student.dob.day student.dob.month student.dob.year Example:
struct Student s = { 101, {15, 8, 2004} }; printf("%d\n", s.dob.year); Output:
2004 13.15 Array of Structures
One of the most useful applications of structures is creating an array where each element is a complete record.
struct Student { int id; float marks; }; struct Student students[3]; Access an element and its member using:
students[0].id students[0].marks students[1].id students[1].marks Example
#include <stdio.h> struct Student { int id; int marks; }; int main(void) { struct Student students[3] = { {101, 78}, {102, 91}, {103, 84} }; for (int i = 0; i < 3; i++) { printf("ID = %d, Marks = %d\n", students[i].id, students[i].marks); } return 0; } students Index 0 ┌──────────────────┐ │ id = 101 │ │ marks = 78 │ └──────────────────┘ Index 1 ┌──────────────────┐ │ id = 102 │ │ marks = 91 │ └──────────────────┘ Index 2 ┌──────────────────┐ │ id = 103 │ │ marks = 84 │ └──────────────────┘
13.16 Structures with Functions
A structure can be passed to a function just like other values.
#include <stdio.h> struct Student { int id; float marks; }; void display(struct Student s) { printf("ID = %d\n", s.id); printf("Marks = %.2f\n", s.marks); } int main(void) { struct Student s = {101, 88.5f}; display(s); return 0; } Here the structure is passed by value.
The function receives its own parameter object containing the copied structure value.
13.17 Passing a Structure by Value
struct Point { int x; int y; }; void change(struct Point p) { p.x = 100; } int main(void) { struct Point point = {10, 20}; change(point); printf("%d\n", point.x); return 0; } The output remains:
10 Why?
C passes the structure argument by value. The function changes its parameter copy, not the caller's object.
13.18 Passing a Structure Using a Pointer
If a function needs to modify the original structure, pass its address.
#include <stdio.h> struct Student { int id; int marks; }; void updateMarks(struct Student *p) { p->marks = 95; } int main(void) { struct Student s = {101, 80}; updateMarks(&s); printf("Marks = %d\n", s.marks); return 0; } Output:
Marks = 95 The pointer allows the function to access the original structure object.
13.19 The -> Operator
When you have a pointer to a structure, use -> to access its members.
p->marks This is equivalent to:
(*p).marks struct Student s = {101, 85}; struct Student *p = &s; p │ │ stores address of s ▼ ┌───────────────────────────────┐ │ s │ ├──────────────┬────────────────┤ │ id │ 101 │ ├──────────────┼────────────────┤ │ marks │ 85 │ └──────────────┴────────────────┘ p->marks │ └──── accesses s.marks p->marks == (*p).marks 13.20 . vs ->
| Situation | Operator | Example |
|---|---|---|
| Structure object | . | s.marks |
| Pointer to structure | -> | p->marks |
| Pointer expanded form | * and . | (*p).marks |
p->member means (*p).member. The parentheses are important in the expanded form. 13.21 Modifying a Structure Through a Pointer
struct Employee { int id; float salary; }; int main(void) { struct Employee e = {101, 45000.0f}; struct Employee *p = &e; p->salary = 50000.0f; printf("%.2f\n", e.salary); return 0; } Since p points to e, modifying p->salary modifies e.salary.
13.22 Returning a Structure from a Function
A function can return a structure value.
#include <stdio.h> struct Point { int x; int y; }; struct Point createPoint(int x, int y) { struct Point p = {x, y}; return p; } int main(void) { struct Point result; result = createPoint(10, 20); printf("(%d, %d)\n", result.x, result.y); return 0; } Returning the structure by value is valid.
13.23 Structure Size and sizeof
You can determine the size of a structure object using sizeof.
printf("%zu\n", sizeof(struct Student)); But do not assume that the structure size is always exactly the sum of the sizes of its members.
The implementation may insert padding bytes to satisfy alignment requirements.
Possible memory layout ┌───────────────┐ │ member A │ ├───────────────┤ │ padding │ ├───────────────┤ │ member B │ ├───────────────┤ │ padding │ └───────────────┘ Padding depends on the implementation, member types and alignment requirements.
sizeof(struct S) must equal the simple sum of all member sizeof values. 13.24 Structure Alignment and Padding
Different types may have different alignment requirements. A compiler can insert unused bytes between members or at the end of a structure.
struct Example { char c; int x; }; It is possible for padding to appear between c and x.
The exact layout is implementation-dependent.
Why padding?
To place members at suitable memory boundaries required by the target architecture and ABI.
Why does it matter?
Structure size affects memory usage, arrays of structures and binary data layouts.
13.25 typedef with Structures — Preview
C also allows a type alias to be created with typedef.
typedef struct { int id; float marks; } Student; Then:
Student s1; instead of:
struct Student s1; typedef has several important uses beyond structures and will be covered separately in the Enumerations & typedef topic. 13.26 Bit-Fields — Advanced Preview
C structures can also contain bit-fields. They allow an implementation-defined allocation of a specified number of bits for certain members.
struct Flags { unsigned int ready : 1; unsigned int mode : 2; }; Bit-fields are useful in some low-level programming, embedded systems and hardware-oriented code.
13.27 What Is a Union?
A union is another user-defined type that contains multiple members.
The key difference is that the members share the same storage.
union Data { int number; float price; char letter; }; A union object has storage that is shared by its members.
Union: members overlap in shared storage.
13.28 Union Syntax
union UnionName { data_type member1; data_type member2; data_type member3; }; Example:
union Data { int number; float price; }; Create an object:
union Data data; 13.29 Union Memory Sharing
union Data data ┌───────────────────────────────┐ │ │ │ SHARED STORAGE │ │ │ │ number / price / letter │ │ │ └───────────────────────────────┘ All members refer to overlapping storage. They do not each get an independent copy of the storage.
For example:
union Data d; d.number = 100; The union storage now contains the representation written through number.
If you then write:
d.price = 12.5f; the same storage is written again. You should not expect the previous integer value and the new floating-point value to remain independently stored.
13.30 Initializing a Union
A union can be initialized when it is declared.
union Data { int number; float price; }; union Data d = {25}; Without a designated initializer, the first named member is initialized.
A designated initializer can explicitly select a member:
union Data d = { .price = 12.5f }; 13.31 Accessing Union Members
Union members are accessed with the same dot operator used for structure objects.
union Data d; d.number = 50; printf("%d\n", d.number); The syntax is:
unionObject.member The difference is not the member-access operator. The difference is how the members occupy storage.
13.32 Program Tracing: Union Storage
union Data { int number; float price; }; int main(void) { union Data d; d.number = 100; d.price = 12.5f; return 0; } Step 1 d.number = 100 ┌────────────────────────────┐ │ shared storage │ │ representation of 100 │ └────────────────────────────┘ Step 2 d.price = 12.5f ┌────────────────────────────┐ │ shared storage │ │ representation of 12.5f │ └────────────────────────────┘ The second write uses the same storage. The integer value 100 is not independently preserved as another member value.
13.33 Structure vs Union
| Feature | Structure | Union |
|---|---|---|
| Member storage | Separate storage for members | Shared/overlapping storage |
| Values | Members can hold independent values | One shared representation is used at a time |
| Main purpose | Represent a complete record | Represent alternatives sharing storage |
| Member access | . or -> | . or -> |
| Memory usage | Usually reflects storage for all members plus padding | Based on shared storage and alignment requirements |
STRUCTURE ┌──────────────┐ │ int id │ ├──────────────┤ │ float marks │ ├──────────────┤ │ char grade │ └──────────────┘ Members occupy different regions. UNION ┌──────────────┐ │ │ │ shared │ │ storage │ │ │ └──────────────┘ Members overlap.
13.34 When Should You Use a Structure?
Use a structure when multiple pieces of information need to exist together as one complete object.
Student
ID, name, marks, department
Employee
ID, name, salary, department
Product
Code, quantity, price
Point
X and Y coordinates
13.35 When Should You Use a Union?
A union is useful when a program needs different possible interpretations of the same storage and only one of those alternatives is needed at a time.
Typical examples include:
- Variant data representations
- Memory-constrained systems
- Low-level systems programming
- Hardware-oriented representations
13.36 Tagged Union Concept
A common design pattern combines an enum-like tag with a union.
enum DataType { TYPE_INT, TYPE_FLOAT }; struct Value { enum DataType type; union { int number; float price; } data; }; The type member tells the program which union member should be interpreted as the current value.
Value │ ├── type │ ├── TYPE_INT │ └── TYPE_FLOAT │ └── data ├── number └── price
This is a common foundation for implementing variant values safely at the application-design level.
13.37 Program Tracing: Pointer to Structure
struct Student { int id; int marks; }; int main(void) { struct Student s = {101, 85}; struct Student *p = &s; p->marks = 90; return 0; } Initial object s ┌────────────────────┐ │ id = 101 │ │ marks = 85 │ └────────────────────┘ After: p = &s p ───────────────► s │ ├── id = 101 └── marks = 85 After: p->marks = 90 p ───────────────► s │ ├── id = 101 └── marks = 90
The pointer does not create another structure object. It points to the existing one.
13.38 Complete Program: Student Record
#include <stdio.h> struct Student { int id; char name[50]; float marks; }; int main(void) { struct Student student; printf("Enter ID: "); scanf("%d", &student.id); printf("Enter name: "); scanf("%49s", student.name); printf("Enter marks: "); scanf("%f", &student.marks); printf("\nStudent Record\n"); printf("ID = %d\n", student.id); printf("Name = %s\n", student.name); printf("Marks = %.2f\n", student.marks); return 0; } What happens?
- A structure type named
Studentis defined. - A structure object named
studentis created. - The ID is stored in
student.id. - The name is stored in
student.name. - The marks are stored in
student.marks. - Each member is accessed using the dot operator.
13.39 Complete Program: Structure + Function + Pointer
#include <stdio.h> struct Student { int id; int marks; }; void addBonus(struct Student *student) { student->marks += 5; } void display(struct Student student) { printf("ID = %d\n", student.id); printf("Marks = %d\n", student.marks); } int main(void) { struct Student s = {101, 85}; addBonus(&s); display(s); return 0; } This small program combines three important concepts:
Structure
Groups ID and marks.
Pointer
Allows addBonus() to modify the original object.
Function
Separates modification and display logic.
13.40 Common Mistakes
Mistake 1 — Forgetting struct
Student s; This is not valid unless Student has been defined as a typedef name.
Normally write:
struct Student s; Mistake 2 — Using -> with an object
s->marks; If s is a structure object, use:
s.marks; Mistake 3 — Using . with a structure pointer
p.marks; If p is a pointer to structure, use:
p->marks; Mistake 4 — Comparing structures directly
if (s1 == s2) Compare individual members instead.
Mistake 5 — Assuming no padding
Do not assume that structure size equals the sum of all member sizes.
Mistake 6 — Treating union members as independent
Union members share storage. Writing one member affects the shared representation.
13.41 Common Confusions
| Confusion | Correct Understanding |
|---|---|
| Structure and union are the same | Both group members, but their storage models are different. |
. and -> are interchangeable | . is for an object; -> is for a pointer to structure/union. |
| Structure definition creates an object | A definition describes the structure type; an object declaration creates an instance. |
| Structure size is member-size sum | Padding and alignment can increase the size. |
| Union stores all values independently | Its members overlap in shared storage. |
| Passing a structure automatically passes a reference | C passes structure arguments by value. Use a pointer when modification of the original is required. |
13.42 Structure Memory Model
struct Employee e e │ ▼ ┌────────────────────────────────┐ │ id │ ├────────────────────────────────┤ │ name[] │ ├────────────────────────────────┤ │ salary │ ├────────────────────────────────┤ │ possible trailing padding │ └────────────────────────────────┘ Each member has its own storage, although padding may also be present.
For an array of structures, the complete structure object forms each array element.
struct Employee employees[3]; Conceptually:
employees[0] employees[1] employees[2] Each element is a complete structure object, including any padding required by the implementation.
14.17 Quick Revision
📌 Structure member access → .
📌 Structure pointer access → ->
📌 Array of structures → Stores multiple records.
📌 Nested structure → Structure inside another structure.
📌 Union → Members share the same memory.
📌 typedef → Creates a convenient type alias.
📌 Self-referential structure → Important for linked lists.
🎬 Structures & Unions — Memory Relationship
Compare how structures keep members separately while unions share storage.
🎬 Structure vs Union Visualizer
The active stage highlights the main relationship being explained.
🔎 Program Tracing — Structures & Unions
Trace structure initialization, a structure pointer, and member access through the arrow operator.
—
14.18 Quick MCQs
Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.
The keyword struct introduces a structure type in C.
The dot operator accesses a member of a structure or union object.
The arrow operator accesses a structure or union member through a pointer.
Union members overlap the same storage region.
typedef creates an additional name for an existing type.
A self-referential structure can contain a pointer to another object of the same structure type, which is fundamental for linked structures.
14.19 🎯 Practice Problems
Practice structures, arrays of structures, nested structures, pointers, unions, typedef, and self-referential structures. Use 💻 Solve It Yourself first, open Hint only when needed, and use Show Program after attempting the problem.
Problem 1: Create a Student structure containing roll number, name, and marks, initialize one student, and print the fields.
Input: No input.
Output: Print the initialized student data.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
struct Student s = {101, "Anu", 88.5f};
printf("%d %s %.1f", s.roll, s.name, s.marks);
return 0;
}
Problem 2: Read one student's roll number, name, and marks and display the details.
Input: Roll number, one-word name, and marks.
Output: Print the same values.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
struct Student s;
scanf("%d %29s %f", &s.roll, s.name, &s.marks);
printf("%d %s %.1f", s.roll, s.name, s.marks);
return 0;
}
Problem 3: Store five students using an array of structures and print them.
Input: Five lines: roll number, one-word name, marks.
Output: Print five lines in the same order.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
struct Student students[5];
for (int i = 0; i < 5; i++)
scanf("%d %29s %f", &students[i].roll, students[i].name, &students[i].marks);
for (int i = 0; i < 5; i++)
{
printf("%d %s %.1f", students[i].roll, students[i].name, students[i].marks);
if (i < 4)
printf("\n");
}
return 0;
}
Problem 4: Read N students and print the student with the highest marks.
Input: N followed by N lines: roll, one-word name, marks.
Output: Print roll, name, and marks of the highest-scoring student.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
int n;
scanf("%d", &n);
struct Student s[n];
for (int i = 0; i < n; i++)
scanf("%d %29s %f", &s[i].roll, s[i].name, &s[i].marks);
int best = 0;
for (int i = 1; i < n; i++)
{
if (s[i].marks > s[best].marks)
best = i;
}
printf("%d %s %.1f", s[best].roll, s[best].name, s[best].marks);
return 0;
}
Problem 5: Read N students and print the student with the lowest marks.
Input: N followed by N lines: roll, one-word name, marks.
Output: Print roll, name, and marks of the lowest-scoring student.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
int n;
scanf("%d", &n);
struct Student s[n];
for (int i = 0; i < n; i++)
scanf("%d %29s %f", &s[i].roll, s[i].name, &s[i].marks);
int lowest = 0;
for (int i = 1; i < n; i++)
{
if (s[i].marks < s[lowest].marks)
lowest = i;
}
printf("%d %s %.1f", s[lowest].roll, s[lowest].name, s[lowest].marks);
return 0;
}
Problem 6: Read N students and calculate their average marks.
Input: N followed by N lines: roll, one-word name, marks.
Output: Print average marks to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
int n;
double sum = 0;
scanf("%d", &n);
struct Student s[n];
for (int i = 0; i < n; i++)
{
scanf("%d %29s %f", &s[i].roll, s[i].name, &s[i].marks);
sum += s[i].marks;
}
printf("%.2f", sum / n);
return 0;
}
Problem 7: Read N students and search for a student using a roll number.
Input: N, N student records, then target roll number.
Output: Print name and marks if found, otherwise Not Found.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
int n, target;
scanf("%d", &n);
struct Student s[n];
for (int i = 0; i < n; i++)
scanf("%d %29s %f", &s[i].roll, s[i].name, &s[i].marks);
scanf("%d", &target);
for (int i = 0; i < n; i++)
{
if (s[i].roll == target)
{
printf("%s %.1f", s[i].name, s[i].marks);
return 0;
}
}
printf("Not Found");
return 0;
}
Problem 8: Sort student records in ascending order of marks.
Input: N followed by N lines: roll, one-word name, marks.
Output: Print sorted records, one per line.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
int n;
scanf("%d", &n);
struct Student s[n];
for (int i = 0; i < n; i++)
scanf("%d %29s %f", &s[i].roll, s[i].name, &s[i].marks);
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (s[j].marks > s[j + 1].marks)
{
struct Student temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++)
{
printf("%d %s %.1f", s[i].roll, s[i].name, s[i].marks);
if (i < n - 1)
printf("\n");
}
return 0;
}
Problem 9: Create an Employee structure, read monthly salary, and calculate annual salary.
Input: Employee id, one-word name, monthly salary.
Output: Print annual salary to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Employee
{
int id;
char name[30];
double monthlySalary;
};
int main()
{
struct Employee e;
scanf("%d %29s %lf", &e.id, e.name, &e.monthlySalary);
printf("%.2f", e.monthlySalary * 12.0);
return 0;
}
Problem 10: Pass a Student structure to a function and display its members.
Input: Roll number, one-word name, marks.
Output: Print the structure values from the function.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
void display(struct Student s)
{
printf("%d %s %.1f", s.roll, s.name, s.marks);
}
int main()
{
struct Student s;
scanf("%d %29s %f", &s.roll, s.name, &s.marks);
display(s);
return 0;
}
Problem 11: Read two integers through a function that returns a structure containing both values and their sum.
Input: Two integers.
Output: Print the two values and their sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Result
{
int a;
int b;
int sum;
};
struct Result makeResult(int a, int b)
{
struct Result r = {a, b, a + b};
return r;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
struct Result r = makeResult(a, b);
printf("%d %d %d", r.a, r.b, r.sum);
return 0;
}
Problem 12: Read a student record and display it through a structure pointer.
Input: Roll number and marks.
Output: Print both members using the arrow operator.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
float marks;
};
int main()
{
struct Student s;
scanf("%d %f", &s.roll, &s.marks);
struct Student *p = &s;
printf("%d %.1f", p->roll, p->marks);
return 0;
}
Problem 13: Create a nested structure where Student contains a Date of Birth.
Input: Roll number followed by day, month, year.
Output: Print roll and date as DD-MM-YYYY.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Date
{
int day, month, year;
};
struct Student
{
int roll;
struct Date dob;
};
int main()
{
struct Student s;
scanf("%d %d %d %d",
&s.roll,
&s.dob.day,
&s.dob.month,
&s.dob.year);
printf("%d %02d-%02d-%04d",
s.roll,
s.dob.day,
s.dob.month,
s.dob.year);
return 0;
}
Problem 14: Create a Student structure containing an array of five marks and calculate their total.
Input: Five integer marks.
Output: Print the total.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int marks[5];
};
int main()
{
struct Student s;
int total = 0;
for (int i = 0; i < 5; i++)
{
scanf("%d", &s.marks[i]);
total += s.marks[i];
}
printf("%d", total);
return 0;
}
Problem 15: Use typedef to create an Employee type, read id and salary, and print them.
Input: Employee id and salary.
Output: Print id and salary.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
typedef struct
{
int id;
double salary;
} Employee;
int main()
{
Employee e;
scanf("%d %lf", &e.id, &e.salary);
printf("%d %.2f", e.id, e.salary);
return 0;
}
Problem 16: Create a union containing int, float and char members. Assign and print each member one at a time.
Input: An integer, a float, and a character.
Output: Print the value immediately after assigning each corresponding union member.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
union Data
{
int i;
float f;
char c;
};
int main()
{
union Data d;
int i;
float f;
char c;
scanf("%d %f %c", &i, &f, &c);
d.i = i;
printf("%d\n", d.i);
d.f = f;
printf("%.1f\n", d.f);
d.c = c;
printf("%c", d.c);
return 0;
}
Problem 17: Create equivalent structure and union types and print whether the union size is less than or equal to the structure size.
Input: No input.
Output: Print "Union <= Structure".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct S
{
int i;
double d;
char c;
};
union U
{
int i;
double d;
char c;
};
int main()
{
if (sizeof(union U) <= sizeof(struct S))
printf("Union <= Structure");
else
printf("Unexpected");
return 0;
}
Problem 18: Create two Node objects, link the first to the second, and print both values by following the link.
Input: Two integers.
Output: Print the two values.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Node
{
int data;
struct Node *next;
};
int main()
{
int a, b;
scanf("%d %d", &a, &b);
struct Node second = {b, NULL};
struct Node first = {a, &second};
printf("%d %d", first.data, first.next->data);
return 0;
}
Problem 19: Create a BankAccount structure and calculate final balance after a deposit and withdrawal.
Input: Account number, initial balance, deposit, withdrawal.
Output: Print final balance to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct BankAccount
{
int accountNo;
double balance;
};
int main()
{
struct BankAccount account;
double deposit, withdrawal;
scanf("%d %lf %lf %lf",
&account.accountNo,
&account.balance,
&deposit,
&withdrawal);
account.balance += deposit;
account.balance -= withdrawal;
printf("%.2f", account.balance);
return 0;
}
Problem 20: Build a small student management program that reads N student records, displays all records, and searches for a target roll number.
Input: N, then N lines of roll/name/marks, then target roll.
Output: Print all records, then print Found: name marks or Not Found.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
int n, target;
scanf("%d", &n);
struct Student s[n];
for (int i = 0; i < n; i++)
scanf("%d %29s %f", &s[i].roll, s[i].name, &s[i].marks);
for (int i = 0; i < n; i++)
printf("%d %s %.1f\n", s[i].roll, s[i].name, s[i].marks);
scanf("%d", &target);
for (int i = 0; i < n; i++)
{
if (s[i].roll == target)
{
printf("Found: %s %.1f", s[i].name, s[i].marks);
return 0;
}
}
printf("Not Found");
return 0;
}
14.20 Key Takeaway
Structure = Different data + Separate storage
Union = Different data + Shared storage
Structure variable → .
Structure pointer → ->
Self-referential structure → Foundation of Linked Lists
🎤 Structures & Unions — Interview Questions
💡 Structures & Unions — Placement Tips
- For record-based problems, first identify the fields that belong together and define the structure clearly.
- When sorting an array of structures, swap the entire structure object, not only one member.
- Remember the member-access rule: object uses
., pointer uses->. - Do not memorize exact structure sizes across systems; alignment and padding can change the result.
- For unions, remember that members share storage, so treat them as alternative representations rather than independent simultaneous fields.
- Self-referential structures connect this C topic directly to linked lists, trees, and other dynamic data structures.
✍️ Structures & Unions — Extra Practice Questions
- Create a Product structure and find the product with the highest price.
- Store employee joining dates using a nested Date structure and sort by year.
- Create a structure for complex numbers and write functions for addition and subtraction.
- Use a union to store one of several simple sensor value types along with a separate type tag.
- Build a singly linked list node structure and manually connect three nodes.
- Investigate how changing member order affects
sizeoffor a structure on your compiler.