Pr.Pg Next Pg

Double pointer tutorials

  • As the name suggests double pointer points to a pointer variable storing the memory address of the pointer variable.

Double Pointer

  • A double pointer is represented by **.

  • For example we illustrate double pointer as

int **p;

 

 

Example: C Program to illustrate a double pointer

 Sam Madam

// C Program to illustrate a double pointer

#include<stdio.h>

#include<conio.h>

void main()

{

int a=13;

int *p;

int **dp; //pointer to pointer p

p=&a;

dp=&p;

printf("Value of integer a : %d\n",a);

printf("Memory address of integer a : %u\n",&a);

printf("Value of pointer p pointing to integer a : %d\n",*p);

printf("Memory address of pointer p holding the address of integer a : %u\n",&dp);

printf("Value of double pointer dp : %d",**dp);

getch();

}

Output

Value of integer a : 13

Memory address of integer a : 8874

Value of pointer p pointing to integer a : 13

Memory address of pointer p holding the address of integer a : 8866

Value of double pointer dp : 13

 

Passing pointers to functions

  • Pointers are often passed to a function as aruments. This allows data items within the calling portion of the program to be accessed by the function, altered within the function, and then returned to the calling portion of the program in altered form. We refer to this as passing arguments by reference.

  • When an argument is passed by value, the data item is copied to the function,. Thus any alteration made to the data item within the function is not carried over into the calling routine.

  • When an argument is passed by reference, however the address of a data item is passed to the function.

  • The contents of that address can be accessed freely, either within the function or within the calling routine.

  • Moreover, any change that is made to the data item will be recognized in both the function and th calling routine.
    Thus, the use of a pointer as a function argument permits the corresponding data item to be altered globally from within the function.

  • When pointers are used as arguments to a function, some care is required with the formal argument declaraons within the function.

  • Specifically, the formal arguments that are pointers must each be preceded by an asterisk. Also, if a function declaration is included in the calling portion of the program, the data type of each argument that corresponds to a pointer must b followed by an asterisk.


 

Example: C Program to show pointers to functions

Sam Madam

// C Program to show pointers to functions

#include<stdio.h>

int func (int a, int b)

{

printf("\n a = %d\n",a);

printf("\n b = %d\n",b);

return 0;

}

int main(void)

{

int(*fptr)(int,int); // Function pointer

fptr = func; // Assign address to function pointer

func(5,3);

fptr(5,3);

return 0;

}

Output

a = 5

 

b = 3

 

a = 5

 

b = 3

Pr.Pg border                                              Next Pg