Pointers as function Arguments

In this class, we will understand the use of Pointers as function Arguments.

Pointers as function Arguments

We have clearly understood the concepts of pointer variables and the visualization of pointers.

Pointers as function Arguments

So far, we have understood what pointers are, but we haven’t understood the use of pointers.

There are many uses of the pointers in c programming.

One of the important use of pointers is passing them as the function arguments.

We will try to understand the use of passing the arguments of the functions as pointers using the swapping the values of a variable example.

The image below shows the use of arguments as values, NOT as pointers.

Pointers as Function Arguments Example 1
Pointers as Function Arguments Example 1

The objective above program is to swap the values of i and j.

As we pass the values of arguments as values in the swap function, i and j will get assigned to x and y.

With this assignment, we will lose the connectivity of ‘i’ and j.

The swap function will swap the values of x and y but not the i and j.

With this way of a function call, we can not swap the values of i and j.

The image below is the program for swapping the values with arguments as address.

Pointers as Function Arguments Example 2
Pointers as Function Arguments Example 2

In the above program, the swap function calls have the address of the variables i and j.

In the function definition, the parameters x and y are the pointers to store the ‘address of’ variables i and j.

The image below the visualization of the above function call.

Pointers as Function Arguments Function Call Visualization
Pointers as Function Arguments Function Call Visualization

Now the swap function swaps the values i and j as we pass the references of the variables i and j.