Pointers and Functions in C
Functions and pointers work together in two directions. You can send a pointer into a function so it can change your variables, and a function can send a pointer back to you as its return value.
In this lesson you will practise both directions, write the classic swap with pointers, return a pointer to the largest element of an array, and learn the one rule that prevents a famous bug: never return the address of a local variable.
What You Will Learn
- How to pass pointers to a function.
- Why pointer parameters let a function change the caller's data.
- How to return a pointer from a function.
- Which pointers are safe to return.
- Why returning a local variable's address is a bug.
Pointers and Functions Explained
Exam definition: Passing a pointer to a function sends the address of a variable, so the function can read and modify the original through * (call by reference). A function returning a pointer has a return type like int * and gives back an address; that address must stay valid after the function ends.
Memory trick: Returning a local variable's address is like giving a friend the room number of a hotel you are checking out of. When they reach it, the room belongs to someone else. Return only addresses that outlive the function.
Syntax: Pointer Parameters and Pointer Return Types
/* pointer parameters */
void swap(int *a, int *b); /* call: swap(&x, &y); */
void fill(int *arr, int n); /* call: fill(marks, 5); */
/* returning a pointer */
int *largest(int *arr, int n); /* returns an address inside arr */
char *grade_name(int marks); /* returns a pointer to a string */
| Returning… | Safe? | Why |
|---|---|---|
| Address inside an array the caller passed | Yes | The caller's array still exists |
A string literal (return "Pass";) | Yes | Literals live for the whole program |
Address of a static local variable | Yes | Static variables are never destroyed |
Memory from malloc | Yes | Lives until free (Module 12) |
| Address of a normal local variable | No | Destroyed when the function returns: dangling pointer |
Example 1: Swap and Update Using Pointer Parameters
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void apply_discount(float *price, float percent)
{
*price = *price - (*price * percent / 100);
}
int main(void)
{
int x = 5, y = 8;
float shoes = 2000.0f;
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
apply_discount(&shoes, 15);
printf("Shoes after 15%% off: %.2f\n", shoes);
return 0;
}
Output
After swap: x = 8, y = 5 Shoes after 15% off: 1700.00
Code Explanation
swap(&x, &y)passes the addresses of x and y. Inside,apoints to x andbpoints to y.*a = *b;writes y's value into x itself. The three-step swap withtempexchanges the originals.apply_discountchangesshoesin main through*price. No return value is needed.%%inside printf prints a single%sign.
Also see swapping of two numbers using pointer.
How Returning a Pointer Works
A function can return an address so the caller can reach (and even change) that data directly. For example, a function can return a pointer to the largest element: the caller then knows both its value and its position, and can modify it.
marks: [ 67 | 91 | 78 | 85 ]
^
largest(marks, 4) returns this address
caller: *best = 100; -> marks becomes [ 67 | 100 | 78 | 85 ]
Example 2: Functions That Return Pointers (Safely)
#include <stdio.h>
int *largest(int *arr, int n) /* returns an address inside arr */
{
int *best = arr;
int i;
for (i = 1; i < n; i++)
{
if (arr[i] > *best)
best = &arr[i];
}
return best;
}
const char *grade_name(int marks) /* returns a string literal */
{
if (marks >= 90) return "Outstanding";
if (marks >= 75) return "Distinction";
if (marks >= 40) return "Pass";
return "Fail";
}
int *next_token(void) /* returns a static local */
{
static int token = 100; /* survives between calls */
token++;
return &token;
}
int main(void)
{
int marks[] = {67, 91, 78, 85};
int *best = largest(marks, 4);
printf("Highest: %d at index %d (%s)\n", *best, (int)(best - marks), grade_name(*best));
*best = 100; /* change it through the pointer */
printf("After update marks[1] = %d\n", marks[1]);
printf("Token: %d\n", *next_token());
printf("Token: %d\n", *next_token());
return 0;
}
Output
Highest: 91 at index 1 (Outstanding) After update marks[1] = 100 Token: 101 Token: 102
largestreturns&arr[i]: an address inside the caller's array, which still exists after the call.best - marksconverts the returned pointer into an index.grade_namereturns string literals, which live for the whole program. Its return type isconst char *because literals are read-only.static int tokenis created once and keeps its value, so returning its address is safe.
The wrong way: returning a local address
int *bad(void)
{
int result = 42; /* local: destroyed when bad() returns */
return &result; /* compiler warning: address of local variable */
}
/* int *p = bad(); printf("%d", *p); -> garbage or crash (dangling pointer) */
Important Points to Remember
- Pass &variable when a function must change it.
- In the function, use *param to read or write the original.
- Return type int * means the function returns an address.
- Safe to return: caller's array element, string literal, static variable, malloc memory.
- Never return the address of a normal local variable.
- Use const on pointer parameters that are only read.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
swap(x, y) for swap(int *, int *) | Warning, crash | swap(&x, &y) |
Returning &local | Dangling pointer: garbage | Use static, malloc, or a caller's array |
a = b inside swap instead of *a = *b | Only local pointer copies change | Use * |
Returning a local array: char s[20]; return s; | Dangling pointer | Let the caller pass the buffer |
| Not checking a returned pointer for NULL | Crash when nothing was found | if (p != NULL) |
Pointers and Functions Practice Questions
- Why must we pass
&xto a function that changes x? - Write the prototype of a function that returns a pointer to a char.
- Why is returning the address of a local variable wrong?
- Name three kinds of addresses that are safe to return.
- In Example 2, how does the caller find the index of the largest element?
Show answers
- The function needs the address to reach and modify the original variable; otherwise it gets only a copy.
char *f(void);(with any parameters).- The local variable is destroyed when the function returns, so the pointer becomes dangling.
- An element of an array passed by the caller, a string literal, a static variable (also malloc memory).
- By pointer subtraction:
best - marks.
Coding Exercise
Write int *find(int *arr, int n, int key) that returns a pointer to the first element equal to key, or NULL if not found. Use it to change the 30 in {10, 20, 30, 40} to 35.
Show solution
#include <stdio.h>
int *find(int *arr, int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return &arr[i];
return NULL;
}
int main(void)
{
int a[] = {10, 20, 30, 40};
int *p = find(a, 4, 30);
int i;
if (p != NULL)
*p = 35;
if (find(a, 4, 99) == NULL)
printf("99 not found\n");
for (i = 0; i < 4; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
99 not found 10 20 35 40
Quick Quiz: Pointers and Functions (MCQ)
-
To let
void inc(int *n)change x, call:A)
inc(x);B)inc(&x);C)inc(*x);D)inc(**x); -
float *f(void);declares a function that returns:A) A float B) A pointer to float C) Nothing D) A float array
-
Which is unsafe to return?
A)
"Hello"B) Address of a static variable C) Address of a local variable D) Address of a caller's array element -
A pointer to memory that no longer exists is called:
A) NULL pointer B) Void pointer C) Dangling pointer D) Function pointer
-
Inside
swap(int *a, int *b), which line puts b's value into a's variable?A)
a = b;B)*a = *b;C)&a = &b;D)a = *b;
Show answers
- B:
inc(&x); - B: a pointer to float.
- C: address of a local variable.
- C: dangling pointer.
- B:
*a = *b;
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Change caller's variable | Pass &x, use *p |
|---|---|
| Swap | swap(&x, &y) with *a = *b |
| int *f() | Returns an address |
| Safe to return | Caller's data, literal, static, malloc |
| Never return | &local variable |
| Result of that bug | Dangling pointer |
Frequently asked questions
- How do you pass a pointer to a function?
- Declare a pointer parameter (
int *p) and call with the address (f(&x)). - Can a function return a pointer?
- Yes, as long as the address stays valid: not the address of a local variable.
- Why is returning a local variable's address dangerous?
- Locals are destroyed when the function returns, leaving a dangling pointer.
Remember
- Pointer in = function can change your data.
- Pointer out = only if it outlives the function (no hotel rooms!).
Next Topic
Next lesson: Double Pointers in C. You will meet a pointer that stores the address of another pointer.