Array of Pointers in C Programming

Array of pointers

Syntax:
data-type *array-name[expression];

Where,
expression - is the number of elements to be taken in the array.

  • The square bracket over here will take the precedence over the '*' operator.
  • Each element in array-name will hold a pointer to the data-type.

Example : An array of pointers which stores a character of strings

#include <stdio.h>
void main ()
{
    char *names[5] =
    {
         "Prajakta",
         "Ravi",
         "Jaya",
         "Sapna",
         "Prashant"
    };
    int i;
    for ( i = 0; i < 5; i++)
    {
         printf("Value of names[%d] = %s\n", i, names[i] );
    }
}


Output:
Value of names[0] = Prajakta
Value of names[1] = Ravi
Value of names[2] = Jaya
Value of names[3] = Sapna
Value of names[4] = Prashant

Dynamic Memory Allocation

  • The memory that is allocated during run time is called as dynamic memory allocation.
  • The memory in dynamic allocation is allocated and freed whenever it is required so that the space is not wasted.
  • There are four routines which allow this type of function.
They are as follows:

1. malloc : It allocates the memory and returns a pointer to the first byte of the space that is allocated.

2. calloc : The space for an array of elements is allocated and is initialized to 0. Like malloc it also returns a pointer to the memory.

3. realloc : The size of the previous memory allocation is altered.

Example
Say if we have allocated 10 bytes to A by using malloc and we want to increase the memory by 5 bytes we would again use malloc. But if we use malloc the initial 10 bytes may get lost. In this case, we will use realloc which will add 5 bytes to the existing 10 bytes of A.

4. free : The memory which was allocated previously is freed.