What is Pointer?
A Pointer is a variable which stores the address of another variable is called Pointer / Pointer variable.
Pointer variable is a user defined data type.
Size of Pointer variable is depend on the Architecture like 32 bit takes 2 byte.
Declaration of a Pointer
data_type *variable_name;
int *a;
Here, int is data type of pointer variable. “*” is dereference operator use to declare a pointer variable. “a” is variable name.
This pointer variable stores the address of a variable of type integer. So if we need to stores the address of other data type. We can declare a pointer variable of that particular type.
Like , float *b, char *c, double *d etc.
How the Pointer works?
Consider the following example to define a pointer which stores the address of an
integer.
int num=10;
int *p=#
// Here, p stores the address of variable “num” using & (address operator).
Now if we print the value of p is = address of variable “num” and if we print the value of *p is = value of variable “num”.
In this figure, pointer variable stores the address of “num” variable, i.e., ABCD. The value of number variable is 10. But the address of pointer variable p is FGHJ.
Example of Pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int num=10;
int *p;
clrscr();
p=#//stores the address of number variable
printf("Address of num variable is %x \n",p);
// p contains the address of the number therefore printing p gives the address of number.
printf("Value of p variable is %d \n",*p);
// As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p.
getch();
}
Output:
Use of Pointer as Array, Function, Structure
1. Pointer as Array:
int a[10];
int *p[10]=&a; // Variable p of type pointer is pointing to the address of an integer array ”a”.
2. Pointer as Function:
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a function.
3. Pointer as Structure
struct structure {
int i;
float f;
}st;
struct structure *p = &st; // Pointer p is pointing to the address of a structure variable st.
Advantage and Disadvantage of Pointer
Advantage of Pointer:
Pointer is used for dynamic memory Allocation.
Pointer provide direct access of memory.
Reduces the storage space and complexity of the program
Reduces the execution time of the program.
Addresses of objects can be extracted using pointers
Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.
Disadvantage of Pointer:
Uninitialized pointers might cause segmentation fault.
Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
Pointers are slower than normal variables.
If pointers are updated with incorrect values, it might lead to memory corruption.