Introduction to Pointer
Every variable at declared time occupies certain memory locations. In 'C' the possibilityto access and display the address of the memory location of variable using '&' operator with variable name. The pointer variable is required to store the memory address of any variable. The pointer is shown by (*) asterisk symbol.
Defining a Pointer
A Pointer is a variable which contains an address, that is a location (address) of another variable in memory.
Features of a Pointer
1. Execution time with pointer is much faster because data is manipulated with the address i.e. use to direct access to memory location.
2. Pointers save the memory space.
3. The memory is accessed powerfully with the pointers. The pointer assigns memory space and it also releases. Dynamically memory is allocated.
4. Pointers are used with data structures. They are useful for representing two-dimensional or multi-dimensional arrays.
Pointer Declaration and Initialization
Pointers can be defined or declared as follows.
Syntax: data_type *pointer_name;
This shows the compiler three things about the pointer variable. The asterisk (*) shows which the variable is a pointer variable. pointer_name needs a memory location. Pointer points to a variable of type data_type
For example:
int *p;
A pointer declares the variable p as a pointer variable which points to an integer data type. Remember that the type int refers to the data type of the variable being pointed to by p and not the type of the value of the pointer. It may point to a variable using an assignment statement such as-
p = &quantity;
The p now contains the address of quantity. This is called as pointer initialization. Before a pointer is initialized it should not be used.
We may be ensure that the pointer variable always point to the corresponding type of data.
int a;
int *p;
p =&a;
Assigning an absolute address to a pointer variable is prohibited.
int *ptr;
ptr = 4560;
A pointer variable can be initialized in its declaration itself. For example:
int x , *p = &x;
Note-
This is an initialization of p, not *p. and also remember that the target variable x is declared first.
int *p = &x , x;
is not valid. The indirection operator (*) also called the dereference operator is used in two distinct ways with pointers. When a pointer is declared, the star indicates that it is a pointer, not a normal variable. When the pointer is dereferenced, the indirection operator indicates that the value at that memory location stored in the pointer is to be accessed rather than the address itself. The '&' is the address operator and it represents the address of the variable.
Program:
main( )
{
int x, y , *ptr;
x = 10;
ptr = &x;
printf("Value of x is %d\n",x);
printf("%d is stored at address %u\n", x, &x);
printf("%d is stored at address %u\n", *&x, &x);
printf("%d is stored at address %u\n", *ptr, ptr);
*ptr = 25;
printf("\nNow x = %d \n",x);
}