Answers for "realloc()"

1

realloc

int ptr_new = *realloc(void *ptr, size_t size); 
Where 'ptr_new' is the new pointer you want to point to the required Dynamic
memory, 'ptr' is the already existing pointer to a dynamic memory and 'size'
is the new size of dynamic memory that you want to allocate.

Working:
Realloc creates/allocates a new memory in heap with specified size and copies
all the contents from the previous memory pointer to by the pointer 'ptr'.
It the deallocates the memory in heap pointed to by the old pointer i.e, 'ptr'.
Note: pointer 'ptr' should also point to a memory in heap.
Posted by: Guest on July-03-2020
0

realloc()

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

int main()
{
    int *p, i, n;

    printf("Initial size of the array is 4\n\n");
    p = (int*)calloc(4, sizeof(int));

    if(p==NULL)
    {
        printf("Memory allocation failed");
        exit(1); // exit the program
    }

    for(i = 0; i < 4; i++)
    {
        printf("Enter element at index %d: ", i);
        scanf("%d", p+i);
    }

    printf("\nIncreasing the size of the array by 5 elements ...\n ");

    p = (int*)realloc(p, 9 * sizeof(int));

    if(p==NULL)
    {
        printf("Memory allocation failed");
        exit(1); // exit the program
    }

    printf("\nEnter 5 more integers\n\n");

    for(i = 4; i < 9; i++)
    {
        printf("Enter element at index %d: ", i);
        scanf("%d", p+i);
    }

    printf("\nFinal array: \n\n");

    for(i = 0; i < 9; i++)
    {
        printf("%d ", *(p+i) );
    }

    // signal to operating system program ran fine
    return 0;
}
Posted by: Guest on June-21-2021

Browse Popular Code Answers by Language