Nearby lessons

97 of 124

C - Passing Pointers to Functions

Learn how to pass pointers to functions in C — the function receives the address, so it can change the original variables. This is call by reference, the technique behind swap programs and array processing.

Why Pass a Pointer?

When you pass a normal variable, the function gets a copy (call by value) and cannot change the original. When you pass a pointer, the function receives the address and can modify the original variable directly.

In simple words: call by value sends a photocopy; passing a pointer sends the house address — the function can walk in and change things.

The Classic Swap Program

The swap program is the standard example. Without pointers, swap cannot change the original values — with pointers it can:

Example02
CCode Cell
1#include <stdio.h>
2void swap(int *x, int *y) { // receives addresses
3 int temp = *x;
4 *x = *y;
5 *y = temp;
6}
7void main() {
8 int a = 10, b = 20;
9 printf("Before swap: a=%d b=%d\n", a, b);
10 swap(&a, &b); // pass addresses
11 printf("After swap : a=%d b=%d\n", a, b);
12}
Output

Before swap: a=10 b=20
After swap : a=20 b=10
      

Passing an Array to a Function

The name of an array is the address of its first element, so you can pass the array name directly and walk through it with a pointer:

Example03
CCode Cell
1#include <stdio.h>
2int sumArray(int *arr, int size) {
3 int total = 0, i;
4 for (i = 0; i < size; i++) {
5 total = total + *(arr + i);
6 }
7 return total;
8}
9void main() {
10 int marks[5] = {80, 90, 75, 60, 88};
11 printf("Sum = %d\n", sumArray(marks, 5));
12}
Output
Sum = 393

Common Mistakes

  • Forgetting the & when callingswap(a, b) passes copies and nothing changes.
  • Missing * inside the functionx = y changes the addresses, not the values.
  • Declaring int *p, q; — only p is a pointer; q is a plain int.
📝 Key Takeaways
  • Pass &var to give a function the address
  • Inside the function use *param to reach the original
  • An array name is already an address — pass it directly

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1