C function pointer reference

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

When a pointer is passed as an argument to a function, address of the memory location is passed instead of the value.

This is because, pointer stores the location of the memory, and not the value.

Example of Pointer And Functions

Program to swap two number using call by reference.

#include <stdio.h>
void swap(int *n1, int *n2);

int main()
{
    int num1 = 5, num2 = 10;

    // address of num1 and num2 is passed to the swap function
    swap( &num1, &num2);
    printf("Number1 = %d ", num1);
    printf("Number2 = %d", num2);
    return 0;
}

void swap(int * n1, int * n2)
{
    // pointer n1 and n2 points to the address of num1 and num2 respectively
    int temp;
    temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}

Output

Number1 = 10
Number2 = 5

The address of memory location num1 and num2 are passed to the function swap and the pointers *n1 and *n2 accept those values.

So, now the pointer n1 and n2 points to the address of num1 and num2respectively.

When, the value of pointers are changed, the value in the pointed memory location also changes correspondingly.

Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main function.