Structures and Functions in C
Real programs split work into functions: one reads a record, one prints it, one calculates totals. So you need to know how to send a structure into a function and get one back.
In this lesson you will pass structures in three ways (single members, by value, by pointer), return a structure from a function, and pass an array of records. You will also learn which way is fastest and safest.
What You Will Learn
- How to pass individual members.
- How to pass a whole structure by value.
- How to pass a structure by pointer (reference).
- How to return a structure from a function.
- How to pass an array of structures.
- Which method to choose.
Structures and Functions Explained
Exam definition: A structure can be passed to a function by value (a copy of the whole structure is made; changes don't affect the original) or by reference using a pointer (the function works on the original). A function can also return a structure.
Memory trick: Passing by value = handing over a photocopy of the whole file: slow for a thick file, and edits stay on the copy. Passing by pointer = handing over the file's shelf location: quick, and edits change the real file. Add const to say "look, don't touch".
Syntax: Three Ways to Pass a Structure
struct student { int roll; char name[20]; int marks; };
void show_marks(int m); /* 1. pass a member */
show_marks(s.marks);
void print(struct student st); /* 2. pass by value */
print(s);
void update(struct student *sp); /* 3. pass by pointer */
update(&s);
struct student make(int roll, int marks); /* return a structure */
s = make(101, 90);
The structure type must be defined before any function that uses it, usually at the top of the file.
Example 1: By Value vs By Pointer
#include <stdio.h>
struct student
{
int roll;
char name[20];
int marks;
};
void print(const struct student *s) /* read-only pointer */
{
printf("%d %s %d\n", s->roll, s->name, s->marks);
}
void add_grace_value(struct student s) /* gets a copy */
{
s.marks += 10;
}
void add_grace_pointer(struct student *s) /* gets the address */
{
s->marks += 10;
}
int main(void)
{
struct student s = {101, "Asha", 70};
add_grace_value(s);
printf("After by value : ");
print(&s);
add_grace_pointer(&s);
printf("After by pointer: ");
print(&s);
printf("Copy size %zu bytes vs pointer %zu bytes\n", sizeof(s), sizeof(&s));
return 0;
}
Output
After by value : 101 Asha 70 After by pointer: 101 Asha 80 Copy size 28 bytes vs pointer 8 bytes
Code Explanation
add_grace_valuereceives a copy. It adds 10 to the copy, which disappears when the function ends. The original stays 70.add_grace_pointerreceives&sand usess->marks, so it changes the original to 80.printtakesconst struct student *: fast (no copy) and safe (it can't modify).- Passing by value copies 28 bytes here; for a big record (say 500 bytes) inside a loop, that copying adds up. A pointer is always 8 bytes.
How Returning a Structure Works
A function can return only one value, but that value can be a whole structure. This is a clean way to return several results together, like the real and imaginary parts of a complex number.
c1 = 3 + 2i c2 = 1 + 7i
add(c1, c2):
result.re = 3 + 1 = 4
result.im = 2 + 7 = 9
return result -> whole struct copied back to the caller: 4 + 9i
Returning a structure is safe even though result is local, because the value is copied back, not its address.
Example 2: Return a Structure and Pass an Array of Structures
#include <stdio.h>
struct complex
{
float re, im;
};
struct student
{
char name[20];
int marks;
};
struct complex add(struct complex a, struct complex b)
{
struct complex result;
result.re = a.re + b.re;
result.im = a.im + b.im;
return result; /* copied back to the caller */
}
float average(const struct student list[], int n)
{
int i, total = 0;
for (i = 0; i < n; i++)
total += list[i].marks;
return (float) total / n;
}
void add_grace_all(struct student list[], int n, int grace)
{
int i;
for (i = 0; i < n; i++)
list[i].marks += grace; /* changes the caller's array */
}
int main(void)
{
struct complex c1 = {3, 2}, c2 = {1, 7}, sum;
struct student cls[3] = { {"Asha", 70}, {"Ravi", 55}, {"Neha", 85} };
sum = add(c1, c2);
printf("(%.0f + %.0fi) + (%.0f + %.0fi) = %.0f + %.0fi\n",
c1.re, c1.im, c2.re, c2.im, sum.re, sum.im);
printf("Average before: %.2f\n", average(cls, 3));
add_grace_all(cls, 3, 5);
printf("Average after : %.2f\n", average(cls, 3));
printf("Ravi now has : %d\n", cls[1].marks);
return 0;
}
Output
(3 + 2i) + (1 + 7i) = 4 + 9i Average before: 70.00 Average after : 75.00 Ravi now has : 60
addtakes two structures by value (they are small) and returns a new one.- An array of structures is passed like any array: as the address of its first element. So
add_grace_allchanges the caller's records without any&. const struct student list[]inaveragepromises not to change the records.
Which Method Should You Use?
| Method | Copies | Can change original? | Best for |
|---|---|---|---|
| Pass a member | Just that member | No | Function needs one field |
| By value | Whole structure | No | Small structures, read only |
| By pointer | One address | Yes | Updating, or large structures |
By const pointer | One address | No (enforced) | Large read-only structures |
| Return a structure | Result copied back | n/a | Returning several values together |
Important Points to Remember
- Define the structure before the functions that use it.
- By value = copy; changes are lost.
- By pointer = address; changes stick; use
->. - Use const struct X * for big read-only structures.
- Functions can return a structure (the value is copied back).
- An array of structures is passed by address automatically.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| Defining the struct after the function | Error/warning: struct declared inside parameter list | Define it at the top |
| Expecting a by-value function to update | Original unchanged | Pass a pointer |
Using s.marks on a pointer parameter | Compile error | s->marks |
Calling update(s) for update(struct student *) | Type error | update(&s) |
Returning &local_struct | Dangling pointer | Return the struct by value |
Structures and Functions Practice Questions
- What is the difference between passing a structure by value and by pointer?
- Write the prototype of a function that returns a
struct pointand takes two ints. - Why is passing a large structure by pointer better?
- Is it safe to return a local structure variable? Is it safe to return its address?
- Why doesn't passing an array of structures need
&?
Show answers
- By value copies the whole structure (original unchanged); by pointer passes its address (original can be changed, and nothing big is copied).
struct point make_point(int x, int y);- Only an address is copied instead of all the members, so it's faster and uses less memory.
- Returning the structure (by value) is safe; returning its address is not (dangling pointer).
- An array name already becomes the address of its first element.
Coding Exercise
Create struct distance { int feet; int inch; }. Write struct distance add_dist(struct distance a, struct distance b) that adds two distances (12 inches = 1 foot). Add 5'9" and 3'7".
Show solution
#include <stdio.h>
struct distance { int feet; int inch; };
struct distance add_dist(struct distance a, struct distance b)
{
struct distance r;
r.inch = a.inch + b.inch;
r.feet = a.feet + b.feet + r.inch / 12;
r.inch = r.inch % 12;
return r;
}
int main(void)
{
struct distance d1 = {5, 9}, d2 = {3, 7};
struct distance t = add_dist(d1, d2);
printf("Total = %d feet %d inches\n", t.feet, t.inch);
return 0;
}
Total = 9 feet 4 inches
Quick Quiz: Structures and Functions (MCQ)
-
When a structure is passed by value:
A) Its address is passed B) A copy is passed C) Only the first member is passed D) It is not allowed
-
To let a function modify a structure s, call it with:
A)
f(s)B)f(&s)C)f(*s)D)f(s.member) -
Can a C function return a structure?
A) No B) Yes C) Only a pointer D) Only in C++
-
Inside
void f(struct student *p), marks is accessed as:A)
p.marksB)p->marksC)*p->marksD)&p.marks -
Best parameter for a large structure that is only read:
A)
struct big bB)struct big *bC)const struct big *bD)struct big **b
Show answers
- B: a copy.
- B:
f(&s). - B: yes.
- B:
p->marks. - C:
const struct big *b.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| By value | Copy; original unchanged |
|---|---|
| By pointer | Address; original can change; use -> |
| Large, read-only | const struct X * |
| Return a struct | Allowed, value copied back |
| Return &local struct | Never (dangling) |
| Array of structs | Passed by address automatically |
Frequently asked questions
- How do you pass a structure to a function in C?
- By value (
f(s), a copy) or by pointer (f(&s), the original), or pass single members. - Can a function return a structure?
- Yes. The whole structure is copied back to the caller.
- Why pass a structure by pointer?
- To modify it, and to avoid copying a large structure.
Remember
- By value = photocopy of the file; by pointer = shelf location.
- Big and read-only? const pointer.
Next Topic
Next lesson: Unions in C. You will learn unions, where all members share the same memory.