Most developers encounter pointers in C through a specific mechanism known as pass-by-pointer. It isn’t just a syntax quirk; it is the fundamental reason functions can modify external state. You have likely seen this before without realizing it. Consider the scanf function. Every time you call scanf, you are forced to prepend the address-of operator (& ) to your variables.
scanf("%d", &myNumber);
If you omit that ampersand, the program crashes. Why? Because scanf expects a memory address, not a value. Understanding this behavior unlocks the logic behind how C handles function parameters. When you pass a pointer, you are granting a function permission to reach into your memory and rewrite data directly.
Зміст
The Failure of Pass-by-Value
To grasp why pointers are necessary, we must look at what happens when they are absent. A common beginner mistake is attempting to write a swap function that exchanges two integer values.
Here is a naive implementation that fails:
Run this code. The output will show 5 10 followed by 5 10. The swap did not occur.
The reason is simple. In C, arguments are passed by value by default. When swap(a, b) is called, the system creates local copies of a and b named i and j. The function swaps the values of i and j perfectly well. But when the function returns, those local variables are destroyed. The original a and b in main remain untouched.
The Solution: Pass-by-Pointer
To modify the original variables, the function needs access to their actual memory locations, not copies of their values. This is where pointers for function parameters become essential.
Here is the corrected implementation:
Now, the output is 5 10 followed by 10 5. The swap worked.
How Pointer Dereferencing Works
The difference lies in what is passed to the function.
- The Call:
swap(&a, &b)passes the addresses ofaandb. - The Parameters: The function signature
void swap(int *i, int *j)declaresiandjas pointers to integers. - The Connection: Inside
swap,iholds the address ofa.jholds the address ofb. - The Dereference: The statement
*i = *jmeans “go to the memory address stored ini, and write the value found at the memory address stored injinto it.”
Visually, imagine two boxes labeled a and b.
– a contains 5.
– b contains 10.
– i is a note with the address of box a written on it.
– j is a note with the address of box b written on it.
When the code executes t = *i, it reads the note i, goes to that location, and reads the value 5. It stores 5 in t. Then *i = *j reads the value from box b (which is 10 ) and writes it back into box a. The original boxes have changed.
























