![]() |
VOOZH | about |
In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program.
In C, variables are passed by pointer in the following cases:
A pointer allows the called function to modify a local variable of the caller function.
Example
In the below example program fun() can modify the local variable x of main().
New value of x is 20
If an argument is large, the pass-by pointer is more efficient because only an address is really passed, not the entire object.
Example
The below example demonstrates the use pass-by pointer for passing large-sized arguments. consider the following Employee class and a function printEmpDetails() that prints Employee details.
Name: geek Designation: Software Engineer
The problem with the above code is that every time printEmpDetails() is called, a new Employee object is constructed that involves creating a copy of all data members. So a better implementation would be to pass Employee as a pointer.
Name: geek Designation: Software Engineer
Note This point is valid only for struct as we don't get any efficiency advantage for basic types like int, char, etc.
We can make a function polymorphic by passing objects as a pointer to it.
Example
In the below program, print() receives a pointer to the base class object. Function print() calls the base class function show() if the base class object is passed, and the derived class function show() if the derived class object is passed.
In base In derived
When you want to return multiple values from a function, passing pointers as function parameters allows us to modify the values of variables passed to the function.
Example
Sum is: 12 Product is: 35
By passing arguments by pointer to a function we can do modification in the content of dynamically allocated memory. It is mainly used when you want to allocate memory dynamically (by using functions like malloc, calloc, or realloc.
Example
Dynamic value set is: 20
As a side note, it is a recommended practice to make pointer arguments const if they are being passed by pointer only due to reason no. 2 mentioned above. This is recommended to avoid unexpected modifications to the objects.