Unit 7: Pointers
Unit 7: Pointers
Unit 7: Pointers
int a = 10;
int *p;
int **q;
p = &a;
q = &p;
printf ("a=%d", *p);
printf ("\na=%d", **q);
Pointer Arithmetic
• As a pointer holds the memory address of variable, some arithmetic
operations can be performed with pointers.
• C support four arithmetic operators that can be used with pointers,
such as:
Pointer arithmetic Symbol
Addition +
Subtraction -
Increment ++
Decrement --
• Let p = &a = 1001(Suppose) i.e. Base address of an array
• int type pointer
(2-byte space)
p++ = p+1 = 1001 + 2 = 1003 i.e. Address of next element
p = p+5 = 1001 + 10 = 1011 i.e. Address of 5th integer type element.
(4-byte space)
p++ = p+1 = 1001 + 4 = 1005 i.e. Address of next element
p = p+5 = 1001 + 20 = 1021 i.e. Address of 5th integer type element.
• float type pointer
(4-byte space)
p++ = 1001 + 4 = 1005 i.e. Address of next element
p = p+5 = 1001 + 20 = 1021 i.e. Address of 5th float type element.
• char type pointer
(1-byte space)
p++ = 1001 + 1 = 1002 i.e. Address of next element
p = p+5 = 1001 + 5 = 1006 i.e. Address of 5th char type element.
Invalid pointer operation
return 0;
}
Dynamic Memory Allocation (DMA)
• The process of allocating and de-allocating memory during program
execution is called dynamic memory allocation.
• The DMA process reserves the memory required by the program and
allows the program to utilize the memory.
Problems of static memory allocation
DMA continue..
• C language offers 4 dynamic memory allocation functions. They are,
• malloc()
• calloc()
• realloc()
• free()
• These functions are defined within header file stdlib.h.
malloc ()
}
calloc()
}
free ()
• This build in function frees previously allocated space by calloc(), malloc()
or realloc() functions.
• The memory dynamically allocated is not returned to the system until the
programmer returns the memory explicitly.
• This can be done using free() function.
• Thus, the free() function is used to release the space when it is not required.
Syntax:
free(ptr); where, ptr be any pointer to a memory block created already.
realloc ()