Pointer
Pointer is a variable which stores the address of another variable. Since Pointer is also a kind of variable, thus pointer itself will be stored at different memory location.
Example:
#include<stdio.h> void main() { int a = 10: int *ptr; ptr = &a; }
Example can be Explained as:
Point | Variable ‘a’ | Variable ‘ptr’ |
Name of variable | a | ptr |
Type of value that it holds | Integer | Address of Integer ‘a’ |
Value Stored | 10 | 2002 |
Address of Variable | 2002 9Assumption) | 4004 (Assumption |
Example:
#include<stdio.h> void main() { int a = 3; int *ptr, **ptr; ptr = &a; pptr = &ptr; }
It can be explained as,
Point | Variable ‘a’ | Variable ‘ptr’ | Variable ‘pptr’ |
Name of Variable | A | ptr | pptr |
Type of value that it holds | Integer | Address of ‘a’ | Address of ‘ptr’ |
Value Stored | 10 | 2002 | 4004 |
Address of variable | 2002 | 4004 | 6006 |
The above table can be explained as:
- a is the name given for particular memory location of ordinary variable.
- Let us consider it’s Corresponding address be 2002 and the value stored in variable ‘a’ is 10.
- The address of the variable ‘a’ is stored in another integer variable whose name is ‘ptr’ and which is having corresponding address 4004.
- The address of the variable ‘ptr’ is stored in another integer variable whose name is ‘pptr’ and which is having corresponding address 6006.
Free E-books and Notes
Example:
#include<stdio.h> void main() { int *ptr, i; i = 10; //Address of i assigned to the ptr ptr = &i; //Show the value of i using ptr variable printf("value of i = %d", *ptr); }
Key Points of Pointer
- Unlike ordinary variables pointer is special type of variable which stores the address of ordinary variable.
- Pointer can only store integer number because address of any type of variable is considered as integer.
- It is always better to initialize the pointer immediately after declaration.
- & symbol is used to get address of a variable.
- symbol is used to get value from the address given by pointer.
Advantages of Using Pointer
There are many reasons for using pointers, some of these are: –
- Sometimes it is more convenient or flexible to work with the address of a variable than the actual variable.
- With the use of pointer program execution becomes fater.
- Pointers are used for storing address of a dynamically allocated block of memory.
- Using a pointer, your program can access any memory location in the computer’s memory.
- Pointers allow a function to pass back more than one value by writing then into memory locations that are accessible to the calling function.
- Using pointers, arrays and structures can be handled in more efficient way.
- Low level system programming can be done through the use of pointers.
- It will become impossible to create complex data structures without pointers. These are link list, tree, graphs, etc.