In C++, pointers allow functions to access and modify the original data instead of working on copies. They provide better control over memory and parameter passing.
- Changes made through pointers affect the actual variables.
- They help improve performance by avoiding unnecessary data copying.
Problems with Normal Parameter Passing
- Changes Are Not Reflected: The function works with a copy of the original variable, so any changes made inside the function are not reflected outside.
- Whole Object Is Copied: For large objects (like strings or arrays), passing by value creates a copy of the object, which consumes more memory and processing time.
1. Passing an Integer by Value
#include <iostream>
using namespace std;
void fun(int x) {
x = x + 5;
}
int main() {
int x = 10;
fun(x);
cout << x; // Output: 10
return 0;
}
Output
10
Explanation: The function fun takes x as an argument and modifies its value. However, the modification is done on a local copy of x, so the original variable remains unchanged.
2. Passing a String by Value
#include <iostream>
using namespace std;
void fun(string s) {
cout << s;
}
int main() {
string s = "geeksforgeeks course";
fun(s);
return 0;
}
Output
geeksforgeeks course
Explanation: Although the string s is printed in the function, a copy of the string is created when the function is called. This can be inefficient for large strings or objects.
Using Pointers in Function Parameters
- Changing Values: By passing a pointer, the function can directly modify the original variable.
- Avoiding Copying of Large Objects: Instead of copying the entire object, only its address is passed, improving efficiency.
1. Passing an Integer by Pointer
#include <iostream>
using namespace std;
void fun(int *p) {
*p = *p + 5;
}
int main() {
int x = 10;
fun(&x);
cout << x; // Output: 15
return 0;
}
Output
15
Explanation: The function fun takes a pointer to x as an argument. By dereferencing the pointer (*p), it directly modifies the value of x. This ensures that the change is reflected outside the function.
2. Passing a String by Pointer
#include <iostream>
using namespace std;
void fun(string *s) {
cout << *s;
}
int main() {
string s = "geeksforgeeks course";
fun(&s);
return 0;
}
Output
geeksforgeeks course
Explanation: Instead of copying the string, the function receives a pointer to the original string. Dereferencing the pointer (*s) allows the function to access and use the string efficiently.