6 Pointer
6 Pointer
A pointer is a variable that stores the address of another variable. Unlike other variables that hold
values of a certain type, pointer holds the address of a variable of same data type
1. While declaring/initializing the pointer variable, * indicates that the variable is a pointer.
2. The address of any variable is given by preceding the variable name with Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that
a is going to contain an integer value. It means that a is going to contain the address of a
variable storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can
be read as 'value at'.
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer variable
is pointing. void type pointer works with all data types, but is not often used.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Once a pointer has been assigned the address of a variable, to access the value of the variable,
pointer is dereferenced, using the indirection operator or dereferencing operator *.
#include <stdio.h>
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = & a; // initializing the pointer
printf("%d", *p); //this will print the value of 'a'
printf("%d", *&a); //this will also print the value of 'a'
printf("%u", &a); //this will print the address of 'a'
printf("%u", p); //this will also print the address of 'a'
printf("%u", &p); //this will print the address of 'p'
return 0;
}
Pointer to Array :
As studied above, we can use a pointer to point to an array, and then we can use that pointer to
access the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
#include <stdio.h>
int main()
{
int m = 5, n = 10, o = 0;
int *p1;
int *p2;
int *p3;
return 0;
}
Advantages of pointer :
1. Use of pointer helps to save memory space.
2. It helps to process data very fast.
3. To achieve efficiency in the program pointers are used.
4. Pointers are used to locate correct value at accurate location.
5. Due to pointers it becomes easy to pass array to function.
Disadvantages :
1. If pointer fails, then reading and writing memory operation also fails.
2. Null pointer reference e leads wrong output.
3. Large program with structure, arrays, function, it is difficult to understand pointer.