POINTERS
POINTERS
Introduction:
• The concept of pointers in C is the prime power of the language.
• Pointers are data, it can access other variable data.
• Pointer data is special because you can use them to access other data.
There are several reasons why we use pointers, and few are listed below.
• A pointer variable can be used to access the array without explicit indexing, especially
for character strings.
• Array of pointers to refer to other blocks of data.
• Dynamic memory allocation is possible only through pointers.
• A function can be called dynamically using pointers (pointer to a function).
Memory map: i
3
65524
i – variable / location name
3 – value of location
65524 – location number (address of the vriable)
We see that the compiler has selected memory location 65524 as the place to store the value 3.
Program: 1
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
getch();
}
Output:
Understanding pointers
• When a pointer variable is declared, it is ready to hold a valid memory address.
• This memory address in turn will be having some data value.
Example:
Heap
i
3
ptr 65524 65524
Stack
Here the pointer variable ptr points to memory address 65524, which contains data 3.
data_type *variable_name ;
int *int_ptr;
Example:
float *float_ptr;
• After declaring a pointer variable of particulars type, "it is the responsibility of the
programmer to assign a valid memory address to that variable".
(2) Getting the address dynamically using DMA (Dynamic Memory Allocation: malloc(),
calloc(), realloc() functions ).
Example: 1 int *p;
p = ( int * ) malloc ( sizeof ( int ) ) ;
2 bytes (int) of memory and type casting (int *) done
Example: 2
float *p;
p = ( float *) malloc ( sizeof ( float ) ) ;