Wild Pointer in C | Double Pointers in C
Written by
Wild and Double Pointer :
Wild Pointers:
If a pointer is not initialised to anything, not even NULL, is called a Wild Pointer. The pointer is assigned to a garbage value which may not even be a valid address. Such pointers point to some arbitrary memory location.
Let us look at the code snippet below to understand wild pointers:
int main() { int * ptr; // ptr is a wild pointer int num = 10; p = & x; //ptr is not a wild pointer anymore return 0; }
- ptr is an int type pointer. Since it has not been initialized to anything, not even NULL, it is a wild pointer.
- When ptr is made to point to num, it stores the address of num. Since now ptr is pointing to a valid memory address, it is not a wild pointer anymore.
Double Pointers:
A pointer to a pointer is called a double pointer.
Lets say we have two pointers and a normal variable.
The first pointer stores the address of a variable. The second pointer, which is the double pointer, stores the address of the first pointer. A double pointer is also known as pointer-to-pointer.
Declaring a double pointer is similar to declaring a pointer.
Syntax:
type **pointerName
- typespecifies the type of the pointer. It must a valid type in C.
- ** indicate that the pointer is a double pointer.
- pointerNameis the name of the pointer variable.
Let us look at a code snippet to understand double pointers:
#include<stdio.h> int main() { int num = 10; //normal variable int *ptr1; // pointer for num int **ptr2; // double pointer for ptr1 ptr1 = # // assigning address of num in ptr1 ptr2 = &ptr1; // assigning address of ptr1 in ptr2 printf("Value of num = %d\n", num ); printf("Value of num using single pointer = %d\n", *ptr1 ); printf("Value of num using double pointer = %d\n", **ptr2); }
- We have created an int type variable numthat stores value 10
- We have created a pointer ptr1to point to num
- We have created a pointer ptr2 to point to ptr1
- ptr1 stores the address of numand ptr2 stores the address of ptr1
The above code snippet gives the following output:
Value of num = 10 Value of num using single pointer = 10 Value of num using double pointer = 10
The diagram is a pictorial representation of the above code.
Some important statements to remember concerning single and double pointers:
Statement | Output |
*ptr1 | 10 |
**ptr2 | 10 |
ptr1 | &num (i.e. address of num) |
ptr2 | &ptr1 (i.e. address of ptr) |