Pointers
The pointer is an entity that contains a memory address.
Definition:
Pointers are variables that hold the address of another variable of the same data type.
Uses of Pointers:
• Accessing array elements
• Passing arguments to functions by reference (arguments can be modified)
• Passing arrays and strings to functions
• Build data structures like linked lists, trees, graphs, etc.
• Obtaining memory from the system dynamically
• It reduces the length and the program execution time.
Concept of Pointer:
Whenever a variable is declared, the system will allocate a location to that variable in the memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 1000 for a variable a.
int a = 10 ;
We can access the value 10 by either using the variable name a or the address 1000. Since the memory addresses are simply numbers that can be assigned to some other variable.
The variable that holds memory addresses is called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address, which is the location of another variable. The value of the pointer variable will be stored in another memory location.
Declaring a pointer variable:
The general syntax of pointer declaration is:
data-type *pointer_name;
The data type of pointer must be the same as the variable, which the pointer is pointing.
Initialization of Pointer variable:
Pointer Initialization is the address assignment process for a variable to the pointer variable. The pointer variable contains the address for a variable with the same data type. In C language address operator & is used for setting the address of a variable.The & (which immediately precedes a variable name) returns the address of the variable related to it.
int a = 10 ; int *ptr ; //pointer declaration ptr = &a ; //pointer initialization (or) int *ptr = &a; //initializing and declaring together.
Example:
#include<stdio.h>
main()
{
int i,j,*k;
j=&i;
k=&i;
printf("Enter a value:");
scanf("%d",j); /* Assigning a value into address of 'i' but not in address of 'j' */
printf("%d\n",i);
printf("%d",*k);
}
Example program1:
#include<stdio.h>
int main()
{
int a = 10;
int *ptr;
ptr = &a;
printf("\nValue of a=%d and &a=%d",a,&a);
printf("\nValue of ptr=%d and *ptr=%d",ptr,*ptr);
return(0);
}
Output:
