C Program to Sort a List of Numbers using Pass By Reference

Sreemeenakshi V
2 min readJun 9, 2021

Language Used: C

Pointers:

In C a Pointer is a variable that stores address of another variable. A pointer can also be used to refer to another pointer function.

The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.

Syntax:

int *p1;
int *p2;

How to assign address to pointers?

int* p, c;
c = 7;
p = &c;

Here, the variable c holds the value 7 and the address of the variable c is stored in the pointer p.

Call By Reference:

  • In call by reference, the address of the variable is passed into the function call as the actual parameter.
  • The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
  • Here, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.

Using Pointers:

So basically the task here is to sort the given array using pointers in C.

The array can be fetched with the help of pointers with the pointer variable pointing to the address of the array. Hence in order to sort the array using pointers, we need to access the elements of the array using (pointer + index) format.

Let’s take an example and crack this problem:

Input: n = 7, arr[] = {0, 20, 17, 32, 7, 19, 77}
Output: {0, 7, 17, 19, 20, 32, 77}

Program:

Output:

0, 7, 17, 19, 20, 32, 77

Description:

Here, we are using the function sort to sort the numbers using pointers. For loop is used and iteration is performed if the condition is True and the corresponding statements are executed.

Then using if statement we are storing the values in t to swap it with another pointer variable.

Now print the values in the sorted order.

All these steps are performed by calling the function sort in the main function.

For any educational Assistance,

Refer: https://www.guvi.in/

--

--