Passing a Pointer as an Argument
Introduction
pass arguments to a function in three
ways:
- Call
by Value
- Call
by Reference
- Call
by Pointer
Mainly focus on Call by Pointer
à Passing the address of a variable by &
operator to a function.
Inside the function, a pointer
parameter receives this address and can directly modify the original
variable.
Syntax
void functionName(int *ptr) {
// function body
}
int main() {
int x = 10;
functionName(&x); // passing
address of x
}
Concept Diagram
+-----------+ +--------------------+
|
main() | |
function() |
+-----------+ +--------------------+
| int x=10 |
---> | int *ptr = &x |
| &x (address) -> |
*ptr accesses x |
+-----------+ +--------------------+
→ Both x and *ptr refer to the same
memory location.
Example 1 — Modify
a variable using a pointer
#include <iostream>
using namespace std;
void changeValue(int *p) {
*p = 100; // modifies the
original variable
}
int main() {
int a = 10;
cout << "Before function: " << a << endl;
changeValue(&a); // passing
address of a
cout << "After function: " << a << endl;
return 0;
}
Output:
Before function: 10
After function: 100
Example 2 —
Swapping two numbers using pointers
#include <iostream>
using namespace std;
void swapNumbers(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 5, b = 10;
cout << "Before Swap: a = " << a << ",
b = " << b << endl;
swapNumbers(&a, &b);
cout << "After Swap: a = " << a << ", b
= " << b << endl;
return 0;
}
Output:
Before Swap: a = 5, b = 10
After Swap: a = 10, b = 5
Example 3 —
Passing a pointer to an array
#include <iostream>
using namespace std;
void displayArray(int *arr, int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << "
";
}
int main() {
int num[] = {10, 20, 30, 40};
displayArray(num, 4); // array
name = base address
return 0;
}
Output:
10 20 30 40
The array name acts as a pointer
to its first element.
Advantages
Efficient — avoids copying data
Allows modification of the caller’s variables
Useful for arrays and dynamic memory
Summary Table
|
Drawback |
Explanation |
|
1. Null pointer risk |
Can cause segmentation fault |
|
2. Complex syntax |
Use of * and & reduces
readability |
|
3. Unintended changes |
Directly modifies original
variable |
|
4. Pointer arithmetic |
May corrupt data |
|
5. Security issues |
Exposes raw memory addresses |
|
6. Type unsafety |
Can cast to wrong type |
|
7. Debugging difficulty |
Hard to trace pointer-related
bugs |
Difference Table
|
Type of Call |
Function Prototype |
Passes |
Can Modify? |
|
Call by Value |
void fun(int x) |
Copy of variable |
No |
|
Call by Pointer |
void fun(int *x) |
Address of variable |
Yes |
|
Call by Reference |
void fun(int &x) |
Alias of variable |
Yes |
0 Comments