realloc() to dynamically increase size of an already allocated array

28 Dec 2022 Balmiki Kumar 0 C Programming

Using realloc() Function to Dynamically Increase the Size of an Already Allocated Array in C Programming Language

In C programming language, the realloc() function can be used to dynamically increase the size of an already allocated array. Here's how to use realloc() function:

  1. Declare a pointer variable to the array:

    int *arr;

  2. Allocate memory to the array using malloc() or calloc() function:

    arr = (int *)malloc(sizeof(int) * n);

    where n is the initial size of the array.

  3. Use the array as needed.

  4. If you need to increase the size of the array, use realloc() function:

    arr = (int *)realloc(arr, sizeof(int) * (n + m));

    where m is the additional number of elements to be added to the array.

  5. Use the expanded array as needed.

  6. When finished using the array, free the memory using free() function:

    free(arr);

Note that realloc() function may move the allocated memory block to a new location, so it's important to update the pointer variable accordingly.

In conclusion, realloc() function in C programming language can be used to dynamically increase the size of an already allocated array, making it a useful tool for managing memory efficiently. Understanding the syntax and practical applications of this function can help programmers write more flexible and efficient code.

 

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.