The Wayback Machine - https://web.archive.org/web/20240917191957/https://www.geeksforgeeks.org/when-do-we-pass-arguments-by-reference-or-pointer/
Open In App

When do we pass arguments by pointer?

Last Updated : 08 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

1. To Modify Local Variables of the Function

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(). 

C




// C program to modify local variables of the caller
// function
 
#include <stdio.h>
 
// function to modify local var x
void fun(int* x) {
  *x = 20;
}
 
int main()
{
    int x = 10;
    fun(&x;);
    printf("New value of x is %d", x);
    return 0;
}


Output

New value of x is 20

2. For Passing Large-Sized Arguments

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.

C




// C program to print details of employee using structure
 
#include <stdio.h>
#include <string.h>
 
// Structure to represent Employee
struct Employee {
    char name[50];
    char desig[50];
};
 
// Function to print Employee details
void printEmpDetails(const struct Employee emp)
{
    printf("Name: %s\n", emp.name);
    printf("Designation: %s\n", emp.desig);
}
 
int main()
{
    // Create an instance of Employee
    struct Employee emp1;
    strcpy(emp1.name, "geek");
    strcpy(emp1.desig, "Software Engineer");
 
    // Call the printEmpDetails function
    printEmpDetails(emp1);
 
    return 0;
}


Output

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.

C




// C program to print details of employee using structure
 
#include <stdio.h>
#include <string.h>
 
// Structure to represent Employee
struct Employee {
    char name[50];
    char desig[50];
};
 
// Function to print Employee details
void printEmpDetails(const struct Employee* emp)
{
    printf("Name: %s\n", emp->name);
    printf("Designation: %s\n", emp->desig);
}
 
int main()
{
    // Creating an instance of Employee
    struct Employee emp1;
    strcpy(emp1.name, "geek");
    strcpy(emp1.desig, "Software Engineer");
 
    printEmpDetails(&emp1;);
 
    return 0;
}


Output

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. 

3. To Achieve Run Time Polymorphism in a Function

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.  

C




// C program to achieve run time polymorphism using function
// pointer
 
#include <stdio.h>
 
// Define the base class structure
struct Base {
    void (*show)();
};
 
// Function to show Base
void showBase() { printf("In base\n"); }
 
// Initialize Base
void initBase(struct Base* base) { base->show = showBase; }
 
// Define the derived class structure
struct Derived {
    // Inheritance by including the base class
    struct Base base;
};
 
// Function to show Derived
void showDerived() { printf("In derived\n"); }
 
// Initialize Derived
void initDerived(struct Derived* derived)
{
    // Initialize the base class
    initBase(&(derived->base));
    // Override for Derived behavior
    derived->base.show = showDerived;
}
 
// Function to print using polymorphism
void print(struct Base* base) { base->show(); }
 
// driver code
int main(void)
{
    struct Base b;
    struct Derived d;
 
    initBase(&b;);
    initDerived(&d;);
 
    print(&b;);
   
    // Note: Using a pointer to the base class
    print((struct Base*)&d;);
 
    return 0;
}


Output

In base
In derived

4. To Return Multiple Values

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

C




// C program to return multiple values from a function
 
#include <stdio.h>
 
// Function to calculate sum and product of two numbers
void calcSumAndProduct(int x, int y, int* sum, int* prod)
{
    *sum = x + y;
    *prod = x * y;
}
 
int main()
{
    int x = 5;
    int y = 7;
    int sum, prod;
    // calling the function to calculate sum and product
    calcSumAndProduct(x, y, ∑, ∏);
 
    // printing the sum and product returned from function
    printf("Sum is: %d \nProduct is: %d\n", sum, prod);
 
    return 0;
}


Output

Sum is: 12 
Product is: 35

5. To Modify the Content of Dynamically Allocated Memory.

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

C




// C program to modify dynamically allocated memory
 
#include <stdio.h>
#include <stdlib.h>
 
// Function to allocate memory for an integer and set its
// value
void dynamicMemoryAllocation(int** myptr)
{
    *myptr = (int*)malloc(sizeof(int));
    if (*myptr != NULL) {
        **myptr = 20;
    }
}
 
int main()
{
    int* val;
 
    // calling the function to allocate memory dynamically
    // and set the value
    dynamicMemoryAllocation(&val;);
    printf("Dynamic value set is: %d\n", *val);
    // free up the allocated memory
    free(val);
    return 0;
}


Output

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.

 



Previous Article
Next Article

Similar Reads

C - Pointer to Pointer (Double Pointer)
Prerequisite: Pointers in C The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to cha
5 min read
Difference between Dangling pointer and Void pointer
Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. There are three different ways where Pointer acts as a dangling pointer: By deallocating memoryFunction CallWhen the variable goes out of scope Void pointer: Void pointer is a specific pointer type – void * – a pointer that point
2 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include&lt;stdio.h&gt; int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(&quot;%p\n&quot;, ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
C++ | Function Overloading and Default Arguments | Question 5
Which of the following in Object Oriented Programming is supported by Function overloading and default arguments features of C++. (A) Inheritance (B) Polymorphism (C) Encapsulation (D) None of the above Answer: (B) Explanation: Both of the features allow one function name to work for different parameter. Quiz of this Question
1 min read
C++ | Function Overloading and Default Arguments | Question 2
Output? #include&lt;iostream&gt; using namespace std; int fun(int x = 0, int y = 0, int z) { return (x + y + z); } int main() { cout &lt;&lt; fun(10); return 0; } (A) 10 (B) 0 (C) 20 (D) Compiler Error Answer: (D) Explanation: All default arguments must be the rightmost arguments. The following program works fine and produces 10 as output. #include
1 min read
C++ | Function Overloading and Default Arguments | Question 3
Which of the following overloaded functions are NOT allowed in C++? 1) Function declarations that differ only in the return type int fun(int x, int y); void fun(int x, int y); 2) Functions that differ only by static keyword in return type int fun(int x, int y); static int fun(int x, int y); 3)Parameter declarations that differ only in a pointer * v
1 min read
C++ | Function Overloading and Default Arguments | Question 4
Predict the output of following C++ program. include&lt;iostream&gt; using namespace std; class Test { protected: int x; public: Test (int i):x(i) { } void fun() const { cout &lt;&lt; &quot;fun() const &quot; &lt;&lt; endl; } void fun() { cout &lt;&lt; &quot;fun() &quot; &lt;&lt; endl; } }; int main() { Test t1 (10); const Test t2 (20); t1.fun(); t
1 min read
C++ | Function Overloading and Default Arguments | Question 5
Output of following program? #include &lt;iostream&gt; using namespace std; int fun(int=0, int = 0); int main() { cout &lt;&lt; fun(5); return 0; } int fun(int x, int y) { return (x+y); } (A) Compiler Error (B) 5 (C) 0 (D) 10 Answer: (B) Explanation: The statement "int fun(int=0, int=0)" is declaration of a function that takes two arguments with de
1 min read
C Function Arguments and Function Return Values
Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function
6 min read
How to Count Variable Numbers of Arguments in C?
C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways: 1) By passing first argument as count of arguments. 2) By passing last argument as NULL (or 0). 3) Using some printf (or scanf) like mechanism where first argument ha
2 min read
Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include&lt;iostream&gt; using namespace std; template&lt;class T, class U = char&gt; class A { public: T x; U y; }; int main() { A&lt;char
1 min read
Variable length arguments for Macros
Like functions, we can also pass variable length arguments to macros. For this we will use the following preprocessor identifiers.To support variable length arguments in macro, we must include ellipses (...) in macro definition. There is also "__VA_ARGS__" preprocessing identifier which takes care of variable length argument substitutions which are
2 min read
Some Interesting facts about default arguments in C++
Predict the output of following C++ programs. 1) #include &lt;iostream&gt; void init(int a=1, int b=2, int c=3); int main() { init(); return 0; } void init(int a=1, int b=2, int c=3) { std::cout &lt;&lt; a &lt;&lt; ' ' &lt;&lt; b &lt;&lt; ' ' &lt;&lt; c; } The above program looks correct at first glance but will fail in compilation. If function use
1 min read
Command Line Arguments in C
The most important function of C is the main() function. It is mostly defined with a return type of int and without parameters. int main() { ... } We can also give command-line arguments in C. Command-line arguments are the values given after the name of the program in the command-line shell of Operating Systems. Command-line arguments are handled
4 min read
Pass the value from child process to parent process
Prerequisite: Pipe() and Fork() Basic Write a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process. Examples: Suppose we have an array a[]={1, 2, 3, 4, 5} in child process, then output should be 1 2 3 4 5. Input: 1 2 3 4 5 Output: 1 2 3 4 5 // C p
2 min read
How to Pass or Return a Structure To or From a Function in C?
A structure is a user-defined data type in C. A structure collects several variables in one place. In a structure, each variable is called a member. The types of data contained in a structure can differ from those in an array (e.g., integer, float, character). Syntax: struct geeksforgeeks { char name[20]; int roll_no; char branch[20]; } How to Pass
3 min read
How to pass a 2D array as a parameter in C?
This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subseq
3 min read
Pass Array to Functions in C
In C, the whole array cannot be passed as an argument to a function. However, you can pass a pointer to an array without an index by specifying the array's name. Arrays in C are always passed to the function as pointers pointing to the first element of the array. Syntax In C, we have three ways to pass an array as a parameter to the function. In th
6 min read
How to pass an array by value in C ?
In C, array name represents address and when we pass an array, we actually pass address and the parameter receiving function always accepts them as pointers (even if we use [], refer this for details). How to pass array by value, i.e., how to make sure that we have a new copy of array when we pass it to function? This can be done by wrapping the ar
2 min read
How to declare a pointer to a function?
While a pointer to a variable or an object is used to access them indirectly, a pointer to a function is used to invoke a function indirectly. Well, we assume that you know what it means by a pointer in C. So how do we create a pointer to an integer in C? Huh..it is pretty simple... int *ptrInteger; /*We have put a * operator between int and ptrInt
2 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the &amp; operator array is an alias for &amp;array[0
1 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It
2 min read
NULL Pointer in C
The Null Pointer is the pointer that does not point to any location but NULL. According to C11 standard: “An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guarantee
4 min read
C | Pointer Basics | Question 1
What is the output of following program? # include &lt;stdio.h&gt; void fun(int x) { x = 30; } int main() { int y = 20; fun(y); printf(&quot;%d&quot;, y); return 0; } (A) 30 (B) 20 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using
1 min read
C | Pointer Basics | Question 2
Output of following program? # include &lt;stdio.h&gt; void fun(int *ptr) { *ptr = 30; } int main() { int y = 20; fun(&amp;y); printf(&quot;%d&quot;, y); return 0; } (A) 20 (B) 30 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value
1 min read
C | Pointer Basics | Question 3
Output of following program? #include &lt;stdio.h&gt; int main() { int *ptr; int x; ptr = &amp;x; *ptr = 0; printf(&quot; x = %d\n&quot;, x); printf(&quot; *ptr = %d\n&quot;, *ptr); *ptr += 5; printf(&quot; x = %d\n&quot;, x); printf(&quot; *ptr = %d\n&quot;, *ptr); (*ptr)++; printf(&quot; x = %d\n&quot;, x); printf(&quot; *ptr = %d\n&quot;, *ptr);
2 min read
C | Pointer Basics | Question 4
Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes. #include &lt;stdio.h&gt; int main() { int arri[] = {1, 2 ,3}; int *ptri = arri; char arrc[] = {1, 2 ,3}; char *ptrc = arrc; printf(&quot;sizeof arri[] = %d &quot;, sizeof(arri)); printf(&quot;sizeof ptri = %d &quot;, sizeof(ptri)); printf(&quot;sizeof arrc[] =
1 min read
C | Pointer Basics | Question 17
Assume that float takes 4 bytes, predict the output of following program. #include &lt;stdio.h&gt; int main() { float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &amp;arr[0]; float *ptr2 = ptr1 + 3; printf(&quot;%f &quot;, *ptr2); printf(&quot;%d&quot;, ptr2 - ptr1); return 0; } (A) 90.500000 3 (B) 90.500000 12 (C) 10.000000 12 (D) 0.5000
1 min read
C | Pointer Basics | Question 6
#include&lt;stdio.h&gt; int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf(&quot;Number of elements between two pointer are: %d.&quot;, (ptr2 - ptr1)); printf(&quot;Number of bytes between two pointers are: %d&quot;, (char*)ptr2 - (char*) ptr1); return 0; } Assume that an int variable takes 4 bytes and a
2 min read
C | Pointer Basics | Question 7
#include&lt;stdio.h&gt; int main() { int a; char *x; x = (char *) &amp;a; a = 512; x[0] = 1; x[1] = 2; printf(&quot;%d\n&quot;,a); return 0; } What is the output of above program? (A) Machine dependent (B) 513 (C) 258 (D) Compiler Error Answer: (A) Explanation: Output is 513 in a little endian machine. To understand this output, let integers be sto
1 min read
Article Tags :