What is Pointer in C Programming

Pointer is a variable which store the address of another variable or the value of a pointer is address of another variable. We declare pointer using * sign that is called asterisk.
Declaration of a pointer variable:-
 type * name;

In C language following are some valid declaration of pointer:-
int    *ptr       /* Pointer to an integer */
float  *ptr     /* Pointer to a float */
double *ptr    /* Pointer to a double */
char   *ptr      /* Pointer to a character */

and to store the address of a variable, we use & sign. For example, we want to store the address of variable n that is a integer data type in a variable ptr that is a pointer to integer.For that first we must declare pointer to an integer. 
int n;
int *ptr  /* Pointer to an integer */
and then using & we can store address of variable n.
ptr=&n  /* Store address of variable n in pointer variable ptr */

See the example given below
/* C Program to print value and address */
#include<stdio.h>
int main()
{
 int n=70;
 int *ptr;
 ptr=&n;   /* Store address of n in pointer variable ptr */
 printf("Value of n= %d\n",n);
 printf("Address of n = %u",ptr);
 return 0;
}
/* End of the program */
We can also store the address of variable n at the time of pointer declaration. Following is valid.
int *ptr=&n;  /* Store address of n in pointer variable 

We have seen that ptr prints the address of the variable. To print value of n we use n. But after initializing as ptr = &n;. We can print the value of n by *ptr. See the following program to understand *ptr.
/* C program to print address and vlaue */
#include<stdio.h>
int main()
{
int n=12;
int *ptr=&n;
printf("Address = %u\n",&n);
printf("Value = %d\n",n);
printf("Address = %u\n",ptr);
printf("Value = %d\n",*ptr);
return 0;
}
/* End of the program */
Here is some declaration and initialization of pointers
int n;
char ch;
char *ptr=&n;    /*Invalid */
int *ptr=&ch;   /*invalid */
float *ptr=&n;  /*invalid */
Means we can not initialize one type pointer to store address of another type of variable. Like if we have declared pointer variable as pointer to integer then we can not store address of char in pointer variable.



Popular posts from this blog