Structures in C
A student has a roll number (int), a name (string) and a CGPA (float). An array can't hold these together, because an array stores only one type. A structure can.
In this lesson you will create your own data type with struct, store a student's details in one variable, and learn how to declare, initialize, access and copy structures. Structures are the base of records, files and linked lists, so this lesson matters a lot.
What You Will Learn
- What a structure is and why we need it.
- How to define a structure type.
- How to declare structure variables.
- How to access members with the dot (
.) operator. - How to initialize and copy structures.
- How the size of a structure is decided (padding).
What is a Structure in C?
Exam definition: A structure is a user-defined data type that groups variables of different data types under one name. Each variable inside it is called a member (or field), and members are accessed with the dot operator (.).
Memory trick: A structure is like an admission form. The blank form (the struct definition) has fields: Roll No, Name, CGPA. Every student fills their own copy (a structure variable). Array = many boxes of the same kind; structure = one form with different kinds of boxes.
Syntax of a Structure
struct student /* struct tag: the name of the new type */
{
int roll; /* members */
char name[30];
float cgpa;
}; /* semicolon is required! */
struct student s1; /* declare a variable */
struct student s2 = {101, "Asha", 8.6f}; /* initialize in order */
struct student s3 = {.cgpa = 9.1f, .roll = 102}; /* designated (C99) */
s1.roll = 103; /* access with the dot operator */
- Defining the struct creates a type, not a variable. No memory is used until you declare a variable.
- The type's full name is
struct student(both words).typedefcan shorten it; you'll learn that later in this module. - Members not given in an initializer become 0 (or an empty string).
Example 1: Store and Print a Student Record
#include <stdio.h>
#include <string.h>
struct student
{
int roll;
char name[30];
float cgpa;
};
int main(void)
{
struct student s1 = {101, "Asha Verma", 8.6f};
struct student s2;
s2.roll = 102; /* set members one by one */
strcpy(s2.name, "Ravi Kumar"); /* strings need strcpy */
s2.cgpa = 7.9f;
printf("Roll Name CGPA\n");
printf("%-5d %-12s %.1f\n", s1.roll, s1.name, s1.cgpa);
printf("%-5d %-12s %.1f\n", s2.roll, s2.name, s2.cgpa);
if (s1.cgpa > s2.cgpa)
printf("Topper: %s\n", s1.name);
return 0;
}
Output
Roll Name CGPA 101 Asha Verma 8.6 102 Ravi Kumar 7.9 Topper: Asha Verma
Code Explanation
struct student { ... };defines a new type with three members. It's written outsidemainso every function can use it.s1is initialized in member order: roll, name, cgpa.s2is filled member by member.s2.name = "Ravi"would be an error (arrays can't be assigned), so we usestrcpy.s1.cgpareads "the cgpa member of s1". Members are used like normal variables.
Practice: store student information in a structure and display it.
How a Structure is Stored in Memory
Members are stored in order, one after another. But the compiler may add unused bytes, called padding, so that each member starts at an address the CPU can read quickly (for example, an int at a multiple of 4).
struct demo { char c; int i; char d; }; (typical 64-bit system)
offset: 0 1 2 3 4 5 6 7 8 9 10 11
[c] [pad pad pad][ i ] [d] [pad pad pad]
sizeof(struct demo) = 12, not 1 + 4 + 1 = 6
Reordered: struct demo2 { int i; char c; char d; };
offset: 0 1 2 3 4 5 6 7
[ i ] [c] [d] [pad pad]
sizeof(struct demo2) = 8
So sizeof(struct) ≥ sum of member sizes. Placing bigger members first often saves memory.
Example 2: Copying Structures, Comparing and sizeof
#include <stdio.h>
struct point
{
int x;
int y;
};
struct demo { char c; int i; char d; };
struct demo2 { int i; char c; char d; };
int main(void)
{
struct point a = {3, 4};
struct point b;
b = a; /* whole structure copied at once */
b.x = 10; /* changing b doesn't change a */
printf("a = (%d, %d), b = (%d, %d)\n", a.x, a.y, b.x, b.y);
/* if (a == b) is NOT allowed: compare member by member */
if (a.x == b.x && a.y == b.y)
printf("a and b are equal\n");
else
printf("a and b are different\n");
printf("sizeof(struct point) = %zu\n", sizeof(struct point));
printf("sizeof(struct demo) = %zu\n", sizeof(struct demo));
printf("sizeof(struct demo2) = %zu\n", sizeof(struct demo2));
return 0;
}
Output
a = (3, 4), b = (10, 4) a and b are different sizeof(struct point) = 8 sizeof(struct demo) = 12 sizeof(struct demo2) = 8
b = a;copies every member, even arrays inside the struct. This works for structures, unlike plain arrays.a == bis a compile error. Compare the members you care about.- The sizes show padding:
demoanddemo2have the same members, but different order gives 12 vs 8 bytes. (Sizes can differ on other systems.)
Array vs Structure
| Point | Array | Structure |
|---|---|---|
| Data types | All the same | Can be different |
| Access | By index: a[2] | By name: s.cgpa |
Assign whole thing with = | No | Yes |
| Type | Derived (built from one type) | User-defined |
| Typical use | List of marks | One student's record |
Important Points to Remember
- A structure groups different types under one name.
- End the definition with a semicolon:
}; - Defining a struct creates a type; memory comes with variables.
- Access members with the dot operator:
s.roll. - Structures can be copied with = but not compared with ==.
- sizeof(struct) may be larger than the sum of members because of padding.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Missing ; after } | Confusing compile errors on the next line | Write }; |
student s1; (without struct) | Error: unknown type | struct student s1; or use typedef |
s.name = "Ravi"; | Error: array not assignable | strcpy(s.name, "Ravi"); |
if (s1 == s2) | Compile error | Compare members |
Initializing members inside the definition: int roll = 0; | Compile error in C | Initialize the variable, not the type |
Structures in C Practice Questions
- Define a structure. How is it different from an array?
- Write a structure
bookwith title (40 chars), author (30 chars) and price (float). - Which operator accesses a structure member?
- Can two structure variables be compared with
==? Can they be assigned with=? - Why can
sizeofof a structure be more than the sum of its members?
Show answers
- A user-defined type grouping members of different types under one name. An array holds elements of one type accessed by index.
struct book { char title[40]; char author[30]; float price; };- The dot operator
. - No for
==; yes for=(all members are copied). - The compiler adds padding bytes so members are properly aligned in memory.
Coding Exercise
Create a structure employee with id, name and salary. Store one employee, give a 10% raise using the member, and print the details before and after.
Show solution
#include <stdio.h>
struct employee
{
int id;
char name[30];
float salary;
};
int main(void)
{
struct employee e = {7, "Kiran", 40000.0f};
printf("Before: %d %s %.2f\n", e.id, e.name, e.salary);
e.salary = e.salary * 1.10f;
printf("After : %d %s %.2f\n", e.id, e.name, e.salary);
return 0;
}
Before: 7 Kiran 40000.00 After : 7 Kiran 44000.00
Quick Quiz: Structures in C (MCQ)
-
A structure can hold members of:
A) Only int type B) Only the same type C) Different types D) Only pointers
-
Keyword used to define a structure:
A)
structureB)structC)recordD)class -
Members of a structure variable are accessed with:
A)
->B).C)::D)[] -
Which is invalid for structure variables a and b of the same type?
A)
a = b;B)a.x = b.x;C)if (a == b)D)sizeof(a) -
Extra unused bytes added inside a structure are called:
A) Padding B) Overflow C) Garbage D) Offset
Show answers
- C: different types.
- B:
struct. - B: the dot operator.
- C:
if (a == b). - A: padding.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Structure | User-defined type grouping different types |
|---|---|
| Keyword | struct; definition ends with }; |
| Access member | Dot operator: s.roll |
| s1 = s2 | Allowed: copies all members |
| s1 == s2 | Not allowed |
| sizeof(struct) | ≥ sum of members (padding) |
Frequently asked questions
- What is a structure in C?
- A user-defined data type that groups related variables of different types under one name.
- What is structure padding?
- Unused bytes the compiler inserts so members are aligned for faster access; it makes sizeof bigger than the member total.
- What is the difference between an array and a structure?
- An array stores same-type elements by index; a structure stores different-type members by name.
Remember
- Structure = admission form; variable = one filled copy.
- Don't forget the semicolon after the closing brace.
Next Topic
Next lesson: Array of Structures in C. You will store records of many students in an array of structures.