USE OF MALLOC() AND REALLOC() AND FREE(ptr) in c

 #include <stdio.h>

#include <stdlib.h>

int main()
{
//     // use of malloc
//     int *ptr, n;
//     printf("Enetr the sie of the array you want to create\n");
//     scanf("%d", &n);
//     ptr = (int *)malloc(n * sizeof(int));
//     for (int i = 0; i < n; i++)
//     {
//         printf("Enter the value of no %d of this array\n",i);

//         scanf("%d", &ptr[i]);
//     }
//      for (int i = 0; i < n; i++)
//     {
//         printf("The value at %d of this array is %d\n",i,ptr[i]);
       
//    }

// use of calloc
    int *ptr, n;
    printf("Enetr the sie of the array you want to create\n");
    scanf("%d", &n);
    ptr = (int *)calloc(n , sizeof(int));
    for (int i = 0; i < n; i++)
    {
        printf("Enter the value of no %d of this array\n",i);

        scanf("%d", &ptr[i]);
    }
     for (int i = 0; i < n; i++)
    {
        printf("The value at %d of this array is %d\n",i,ptr[i]);
       
    }


// use of realloc
   
    printf("Enetr the sie of the new array you want to create\n");
    scanf("%d", &n);
    ptr = (int *)realloc(ptr , n*sizeof(int));
    for (int i = 0; i < n; i++)
    {
        printf("Enter the new value of no %d of this array\n",i);

        scanf("%d", &ptr[i]);
    }
     for (int i = 0; i < n; i++)
    {
        printf("The new value at %d of this array is %d\n",i,ptr[i]);
       
    }
    free(ptr);
       
    return 0;
}

OUTPUT:
Enetr the sie of the array you want to create 6 Enter the value of no 0 of this array 789 Enter the value of no 1 of this array 467 Enter the value of no 2 of this array 4565 Enter the value of no 3 of this array 564 Enter the value of no 4 of this array 75 Enter the value of no 5 of this array 56 The value at 0 of this array is 789 The value at 1 of this array is 467 The value at 2 of this array is 4565 The value at 3 of this array is 564 The value at 4 of this array is 75 The value at 5 of this array is 56 Enetr the sie of the new array you want to create

Comments

Post a Comment

Popular posts from this blog

C Program using continue statement

C program of WHILE Loop

NULL Pointer in C.

C Program using DO WHILE loop

C Program using SWITCH statement

New Animated Login or signup page made by HTML, CSS and JavaScript.

C Program to print multiplication table of any number.

C Language Travel Agency Manager Exercise.

STRUCTURE IN C PROGRAMMING.