A pointer is known as derived data type. It is derived from built in data types.
A pointer variable always contains the address of another variable in it. The address represents memory location of computer memory.
A pointer allows us to access and manipulate memory addresses.
Following are the features of pointer:
(1) Pointer allows Dynamic Memory management facility to the C Programmer.
(2) Pointer increases the execution speed of the program.
(3) Pointer Save memory space.
(4) Pointer allows programmer to directly access and manipulate memory addresses. So it is widely used to represent dynamic data structure such as stack, queue, linked list, tree etc…
(5) Pointer allows programmer to pass address of the original variable to the function, so function can works with original variable inside function instead of dummy variables (Call by Reference).
(6) Array and string, can be effectively handled using pointers.
(7) Pointers are also used for file handling.
Declaration of Pointer
The general syntax for declaring pointer variable is given below:
Data Type *Pointer_Name;
Data Type indicates the Data Type of the variable whose address can be stored in Pointer variable.
* indicates that the variable that is followed is pointer variable.
Pointer_Name is a Pointer Variable that can be used to store address of variable of Type Data Type.
ptr is a pointer variable that can hold the address of variables of type int.
If you want to store the address of variable of type float then you can declare a pointer variable as shown below:
Initialization of Pointer Variable
Initialize pointer variable means to assign an address of particular variable to pointer variable.
Pointer variable can be initialized using & operator.
The general syntax for initialize pointer variable is given below:
Pointer_Name = & Variable_Name;
ptr = &x;
We can also initialize pointer variable at the time of its declaration as shown below:
int *ptr = &x;
Access Variable using Pointer
Once a pointer variable is declared and initialized, we can access the value of that variable using pointer variable and * operator. * Operator is known as indirection or dereferencing operator in C.
Consider Following Example:
int x = 10;
int *ptr = &x;
printf (“Value of x is %d”, *ptr);
*ptr is a pointer variable that contains the address of variable x.
Now if we want to access the value of variable x using pointer variable then we can use * operator followed by pointer variable name.
It is also possible to assign value to the variable using pointer variable as shown below:
*ptr = 20;
It will assign value 20 to variable whose address is contained in pointer variable ptr.