Jan 25, 2022

Dynamic Memory Allocation in Heap (C Language)

Using malloc() , calloc() , realloc() and free() Functions.

 #include <stdio.h>

#include <stdlib.h>

// Memory allocation using 'malloc' ,'calloc','realloc',and
//'free' free the memory of allocated pointer
int main(int argc, char const *argv[])
{

    // NOTE :    //pointer return 'NULL' if memory to that pointer is not allocated
    int n;
    printf("Enter the Number : ");
    scanf("%d ", &n);

    //    //'malloc' allocates the memory and leaves the memory uninitialised
    //   // int <pointer> =(typecast_pointer *)malloc(memory_size_to_allocate);
    // name stores the address of first element
    int *arr_malloc_pointer = (int *)malloc(n * sizeof(int));
    //'calloc' allocates the memory and initialises all bits to zero
    //int <pointer>=(typecast_pointer *)calloc(number_of_elements,sizeof('datatype'));
    // name of variable stores the address of first element
    int *arr_calloc_pointer = (int *)calloc(n, sizeof(int));
    for (int i = 0; i < n; i++)
    {
        scanf("%d", arr_malloc_pointer + i);
    }

    //'calloc' set all values to zero
    for (int i = 0; i < n; i++)
    {
        // printf("%d", *(arr_malloc_pointer + i));
        printf("%d ", *(arr_calloc_pointer + i));
    }

    printf("\n");

    //'realloc' reallocates the memory to the pointer if required dynamically
//decrease or increase
    //ptr=realloc(ptr_name,size_to_reallocate)
    arr_malloc_pointer = realloc(arr_malloc_pointer, 2 * n * (sizeof(int)));

    // gives garbage values for next new allocated memory
    for (int i = 0; i < 2 * n; i++)
    {
        printf("\n%d  ", *(arr_malloc_pointer + i));
        // printf("%d ", *(arr_calloc_pointer + i));
    }

    return 0;
}

No comments:

Post a Comment

Comparing two files in C language.

Operations on More than one File.    # include < stdio.h > # include < stdlib.h > # include < string.h > int main ( int ...