C program implementing realloc() functions.

In the example below, we will be using the realloc() function. The realloc() the function will provide the flexibility to the users for changing the size of memory which is previously allocated by the dynamic memory location.

Code:

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

int main()
{
    int *p, i , n1, n2;
    printf("Enter the number of elements that you want to enter in the array: ");
    scanf("%d", &n1);

    p = (int*) calloc(n1 * sizeof(int));

    printf("Addresses of previously allocated memory are: ");
    for(i = 0; i < n1; ++i)
         printf("%u\n",p + i);

    printf("\nEnter the new size of the array: ");
    scanf("%d", &n2);
    p = realloc(p, n2 * sizeof(int));

    printf("Addresses of all newly allocated memory are: ");
    for(i = 0; i < n2; ++i)
         printf("%u\n", p + i);
    return 0;
}

The above code will display its output as below.

Output:

Enter the number of elements that you want to enter in the array: 3
Addresses of previously allocated memory are: 36765476
36765480
36765484
Enter the new size of the array: 3
Addresses of all newly allocated memory are: 36765476
36765480
36765484
36765488
SHARE C program implementing realloc() functions.

You may also like...

Leave a Reply

Your email address will not be published.

Share