This blog is under construction

Monday, 7 October 2013

How to pass a pointer as an argument to function in c?

If we pass arguments to function by reference, then the called function can alter the value of variable in the calling function.

Basically, we pass address of the variables as arguments to the called function.  So, any modification to the value of the arguments of called function is carried out to the calling function.

Below program explains how to pass pointer as argument to function.

  #include <stdio.h>

  void swap(int *num1, int *num2) {
        int tmp;

        /* printing the pointer(arguments) value */
        printf("\nAddresses inside called function:\n");
        printf("Pointer value of num1: 0x%x\n", (int)num1);
        printf("Pointer value of num2: 0x%x\n", (int)num2);

        /* swapping two numbers */
        tmp = *num1;
        *num1 = *num2;
        *num2 = tmp;

  int main() {
        int num1, num2;

        /* get the inputs from the user */
        printf("Enter your first integer:");
        scanf("%d", &num1);
        printf("Enter your second integer:");
        scanf("%d", &num2);

        /* printing values before swap operations */
        printf("\nValues before swapping:\n");
        printf("num1: %d\tnum2: %d\n", num1, num2);

        /* printing address of the variables before calling swap() function */
        printf("\nAddress of the variables inside calling function:\n");
        printf("Address of num1: 0x%x\n", (int)&num1);
        printf("Address of num2: 0x%x\n", (int)&num2);

        /* passing pointer(address of variable) as argument */
        swap(&num1, &num2);

        /* print the values after swap operation */
        printf("\nValues after swapping:\n");
        printf("num1: %d\tnum2: %d\n", num1, num2);
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first integer:100
  Enter your second integer:500

  Values before swapping:
  num1: 100 num2: 500

  Address of the variables inside calling function:
  Address of num1: 0xbfdd3f0c
  Address of num2: 0xbfdd3f08

  Addresses inside called function:
  Pointer value of num1: 0xbfdd3f0c
  Pointer value of num2: 0xbfdd3f08

  Values after swapping:
  num1: 500 num2: 100

No comments:

Post a Comment