Pointers are used to access the variables directly by using their address Locations. The value has been assigned to the variable gets stored in that particular memory location.
A pointer that is assigned NULL is called a "null pointer".The value of null pointer is 0.
A void pointer is also called as generic pointer. It doesn't have any standard data type. In this pointer void keyword is used. It is used to store the address of any variable.
void *p = NULL; //Void pointer
Two types of pointer operators:
& is used to determine the address of the variable.
int a=1; int *aptr; aptr= &a; //aptr gets address of a
* can be used to assign a value to a location in memory.
*aptr=2; //changes a to 2
It contain data type and pointer name with astric sign.
data type *pointer_name;
here, * is pointer variable.
Example :
int *ptr;
This declares that the pointer variable points to an integer data type.
Initialization of pointer variable is done by assigning to it the address of a variable
pointer_name= &variable;
int a=2081; int *ptr; //Declaration of pointer ptr = &a; //Initialization of pointer
[It is completed in function tutorial.]
It is a method of passing arguments to a function copies the address of an actual parameter into the formal parameter.
To pass value by reference, pointer is passed as argument to function call like any other value.
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int *a, int *b) {
int temp;
temp = a; / save the value of a */
a = *b; / put y into a */
b = temp; / put temp into b */
return;
}
Output
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100
#include<stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter any two integers\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of the two numbers = %d\n", sum);
return 0;
}
Output
Enter any two integers 2 3 Sum of the two numbers = 5
#include<stdio.h>
int main( )
{
int num, rem, rev=0 ;
int *pn, *pr ;
printf(" Enter the number \n") ;
scanf("%f ",& num) ;
pn = & num ;
pr = & rev ;
do
{
rem = ( *pn ) % 10 ;
*pr = ( *pr * 10 ) + rem ;
*pn = ( *pn ) / 10 ;
}
while( *pn > 0) ;
printf("\n Reverse of Number is : %d ",*pr) ;
return ( 0 );
}
Output
Enter the number 123 Reverse of Number is : 321
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y, *large, *xptr,*yptr;
clrscr();
printf("Enter the value of x and y \n");
scanf("%d%d",&x,&y);
xptr=&x;
yptr=&y;
if(*xptr>*yptr)
{
large=xptr;
}
else
{
large=yptr;
}
printf("The largest number is : %d",*large);
getch();
}
Output
Enter the value of x and y 34 45 The largest number is : 45