
A pointer is a variable whose value is the address of another variable. Like any variable, you must declare a pointer before storing any variable address. The pointer can be declared using * (asterisk symbol).
Syntax: Pointer declaration
int a=10; int *p; p=&a;
& (ampersand sign) - Determines the address of a variable. * (asterisk sign) - Accesses the value from the assigned address.
Example 1: Program to illustrate the use of address of operator '&'.
void main()
{
int a=10;
printf("\nValue in variable is %d", a); //10
printf("\nAddress of variable is %u",&a);
getch();
}
The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.
Example 2: WAP to illustrate the use of Pointer.
void main()
{
int a=10, *p;
clrscr();
p=&a;
printf("\nValue of A = %d", a); //10
printf("\nAddress of A = %u",&a);
printf("\nValue of p = %u",p);
printf("\nAddress of P = %u",&p);
printf("\nPointer of p = %d",*p); //10
getch();
}
Example 3: Pointer can be use as an arrays.
void main()
{
int a[10],i,*p;
clrscr();
printf("Enter 10 numbers : ");
for(i=0;i<=9;i++)
scanf("%d",&a[i]);
p=a;
printf("\nFirst Value : %d",*p);
p=p+2;
printf("\nAfter adding 2 in p : %d",*p);
p--;
printf("\nAfter subtracting 1 in p : %d",*p);
getch();
}
Example 4: Program passing array to function pointer.
void fun(int *p);
void main()
{
int a[]={1,2,3,4,5};
clrscr();
fun(a);
getch();
}
void fun(int *p)
{
int i;
for(i=1;i<=4;i++)
{
printf("%d",p[i]);
}
}Example 5: Program to use pointer to access string character-wise.
void main()
{
char name[]="C-Language";
char *ptr;
clrscr();
while(*ptr!='\0')
{
printf("%c",*ptr);
ptr++;
}
getch();
}
Advantages of pointer
Ad: