Nearby lessons

56 of 72

C - Passing Pointers to Functions

Learn how to pass a variable's address to a function so the function can change the original value.

Why Pass a Pointer to a Function?

When a normal value is passed to a function, the function receives a copy. If you pass the variable's address, the function can use a pointer to change the original variable.

Example01
CCode Cell
1#include <stdio.h>
2 
3void changeValue(int *ptr)
4{
5 *ptr = 100;
6}
7 
8int main()
9{
10 int number = 10;
11 
12 changeValue(&number);
13 
14 printf("number = %d", number);
15 
16 return 0;
17}
Output
number = 100

Swap Two Numbers Using Pointers

This function swaps the original values because it receives their addresses.

Example02
CCode Cell
1#include <stdio.h>
2 
3void swap(int *x, int *y)
4{
5 int temp = *x;
6 *x = *y;
7 *y = temp;
8}
9 
10int main()
11{
12 int a = 10;
13 int b = 20;
14 
15 printf("Before: a = %d, b = %d\n", a, b);
16 
17 swap(&a, &b);
18 
19 printf("After: a = %d, b = %d\n", a, b);
20 
21 return 0;
22}
Output
Before: a = 10, b = 20
After: a = 20, b = 10

Remember

  • Use &number when calling the function to pass the address.
  • Use a pointer parameter such as int *ptr.
  • Use *ptr to access or change the original value.

In C, this is often called call by reference in beginner lessons, but technically the address is passed by value.

📝 Key Takeaways
  • C passes function arguments by value.
  • Passing an address lets a function access the original variable.
  • Use * inside the function to change the value at that address.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1