C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
// Next section of code would probably be calculations related
// to the per-city data entry
// Don't forget to deallocate the heap memory when done
for (ctr = 0; ctr < 50; ctr++)
{
free(temps[ctr]);
}

Of course, such code requires massive data entry. The values would most likely come from a saved
file instead of from the user. Nevertheless, the code gives you insight into the advanced data
structures available by using the heap. Also, real-world programs aren’t usually of the 20-line variety
you often see in this book. Real-world programs, although not necessarily harder than those here, are
usually many pages long. Throughout the program, some sections might need extra memory, whereas
other sections do not. The heap lets you use memory efficiently.


Figure 26.3 shows you what the heap memory might look like while allocating the temps array
memory (after the first 4 of the 50 malloc() calls). As you can see, temps belongs to the
program’s data area, but the memory each temps element points to belongs to the heap. You can free
up the data temps points to when you no longer need the extra workspace.


FIGURE 26.3 Each temps element points to a different part of the heap.

This has been a long chapter with some complicated material, but you’re almost finished! We just
need to close the chapter with a program that uses both malloc() and free(), as well as shows
you how a small computer program written by you can deal with massive amounts of data.


Click here to view code image


// Example program #1 from Chapter 26 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter26ex1.c
/* The program looks for a number of random integers, allocates an
array and fills it with numbers between 1 and 500 and then loops
through all the numbers and figures out the smallest, the biggest,
and the average. It then frees the memory. */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Free download pdf