Professional Documents
Culture Documents
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in
C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output:
50
Benefits(use) of pointers in c:
Pointer Arithmatic:
There are 4 Arithmetic Operation that can used on Pointer.++,--,+,-
1.int *i
i++;
2.int *I;
i--;
3.int *p1;
int *p2;
*p1+*p2;
4.int *p1;
int *p2;
*p1-*p2;
int main()
{
int m = 5, n = 10, o = 0;
int *p1;
int *p2;
int *p3;
o = *p1+*p2;
p3 = p1-p2;
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
return 0;
Output:
p1 = 2680016
p2 = 2680012
*p1+*p2 = 15
p1-p2 = 1
p1++ = 2680020
p2-- = 2680008
Array of pointers:
#include <stdio.h>
int main () {
int i, *ptr[MAX];
return 0;
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Example:
#include <stdio.h>
void salaryhike(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
printf("Enter the employee current salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;
}
Output:
#include <stdio.h>
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10