How it works...

The user will be asked to specify the number of elements. The value entered by the user will be assigned to the variable n. Let's assume the value entered by the user is 4, which is then assigned to the variable n. Using the calloc function, 4 memory blocks are dynamically allocated, where the size of each memory block is equal to the size consumed by an int data type. In other words, a memory block that can store four integer values is dynamically allocated and a pointer, ptr, is set to point to it. If the ptr pointer is NULL, then this means that the memory could not be allocated and the program will terminate after displaying an error message.

If the memory is successfully allocated, the user will be asked to enter four integer values. The values entered will be assigned to individual memory blocks pointed to by the pointer, ptr. The integer values entered by the user are then displayed on the screen. The user will then be asked if they want to add more elements. Assuming that the user wants to add two more memory blocks to the existing allocated ones, the value of 2 entered by the user will be assigned to the variable m.

Using the realloc function, the quantity of the memory blocks increases from four to six, where each memory block is able to store an integer number. The user will be asked to enter the integer values for two newly added memory blocks. To indicate that the size of memory blocks has increased from four to six, all of the six integers assigned to the memory blocks are displayed on the screen. Thereafter, the user will be asked how many blocks they want to keep out of the six memory blocks. Let's assume the value entered by the user is 3; that is, the user wants to keep the integers in the first three memory blocks and discard the rest.

The value of 3 entered by the user will be assigned to the variable m. Again, the realloc function is invoked to reduce the number of memory blocks from six to three. Finally, the integers in the three memory blocks are displayed on the screen.

The program is compiled using GCC, as shown in the following screenshot. Because no error appears during compilation, the dynamicmem.c program has successfully compiled into a .exe file: dynamicmem.exe. Upon executing this file, the user is prompted to define how many memory blocks they want to dynamically allocate. After that, the user is asked how many additional memory blocks they want. The user is also asked whether they want to keep some memory blocks active from the total, thereby reducing the number of allocated memory blocks, and, finally, all the memory blocks are freed. All of the actions appear as follows:

Figure 14.4

Now, let's move on to the next recipe!