C reading & accessing array using malloc()



Reading & Accessing array using Malloc function

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

void main()
{
clrscr();
int *ptr,*temp;
int i;

ptr = (int *)malloc(4*sizeof(int));  // Allocating 8 bytes
temp = ptr;  // Storing Current Pointer Value

for(i=0;i < 4;i++)
     {
     printf("Enter the Number %d : ",i);
     scanf("%d",ptr);
     ptr++;          // New Location i.e increment Pointer
     }

ptr = temp;
   for(i=0;i < 4;i++)
   {
   printf("\nNumber(%d) : %d",i,*ptr);
   ptr++;
   }

getch();
}

Output :

Enter the Number 0 : 45
Enter the Number 1 : 35
Enter the Number 2 : 25
Enter the Number 3 : 15

Number(0) : 45
Number(1) : 35
Number(2) : 25
Number(3) : 15

Explanation of Code:

ptr = (int *)malloc(4*sizeof(int));
  1. Above Statement will allocate 8 bytes i.e we can store 4 integer values
  2. Starting address of allocated block is Stored in Pointer ptr.
  3. As we are using again that pointer address for Printing the Elements so store it in temporary Pointer variable
  4. In for Loop Accept value using scanf and Increment Pointer so that it points to next location

Same Program using Calloc function :

Step 1 : Memory is allocated using

ptr = (int *)malloc(4*sizeof(int));

Step 2 : Replace the Above statement by Following Statement

ptr = (int *)calloc(4,sizeof(int));