In Unit 5 a swap function failed because C passes arguments by value. Pointers solve the problem: pass the addresses of the variables, and the function can reach the originals. This section shows the technique and two related topics: returning several results, and functions that return pointers.
Call by reference using pointers
Call by value
Call by reference (pointers)
What is passed
A copy of the value
A copy of the address
Call
swapVal(x, y);
swapRef(&x, &y);
Parameters
int a, int b
int *pa, int *pb
Access in the function
a, b
*pa, *pb
Can change the caller’s variables
No
Yes
Returning more than one value
A return statement gives back one value. To deliver several results, the caller passes the addresses of variables in which the function stores them.
Functions returning a pointer
A function can return an address; its return type is then a pointer type, such as int *find_max(int a[], int n). The address returned must still be valid after the function ends:
Safe to return the address of
Not safe
An element of an array passed in by the caller
A local (automatic) variable of the function
A static or global variable
Memory obtained with malloc
A pointer to an object that no longer exists is called a dangling pointer.
Pointers to structures
When a pointer points to a structure, its members are reached with the arrow operator ->: p->member means (*p).member. Passing a structure’s address lets a function change the original without copying the whole structure.
C · struct_pointer.c
#include <stdio.h>struct acc { int balance;};void deposit(struct acc *a, int amount){ a->balance = a->balance + amount; /* same as (*a).balance */}int main(void){ struct acc mine = { 1000 }; deposit(&mine, 500); printf("%d\n", mine.balance); return 0;}
Output
1500
Key takeaways
Pass addresses (&x) and receive them in pointer parameters to change the caller’s variables.
The pointer itself is still passed by value.
Several results can be returned through pointer parameters.
A returned pointer must refer to something that still exists; p->m accesses a member through a structure pointer.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function min_max that receives an integer array and its size and gives back both the smallest and the largest element through pointer parameters, and show a call.
Show worked answer
void min_max(int a[], int n, int *min, int *max) { int i; *min = a[0]; *max = a[0]; for (i = 1; i < n; i++) { if (a[i] < *min) *min = a[i]; if (a[i] > *max) *max = a[i]; } }. Call: int lo, hi; min_max(marks, 5, &lo, &hi);. The addresses of lo and hi are passed, so the assignments to *min and *max inside the function store the two results directly in the caller’s variables.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/pointers/passing-pointers-to-functions/ to read this page.