Previous: 14.2.1 Library Functions for Dynamic Allocation
Up: 14.2 Dynamic Memory Allocation
Previous Page: 14.2.1 Library Functions for Dynamic Allocation
Next Page: 14.3 Pointers to Functions

14.2.2 Dynamic Arrays

Our next example allocates a block of memory dynamically for a number of elements of structure type. It reads data into the elements and prints the data. Once the returned pointer is cast to an appropriate type, the allocated memory block may be treated as an array of elements, with the returned pointer a pointer to the array. The code is shown in Figure 14.15.

Sample Session:

Dynamic memory allocation can also be performed by the library function calloc(), and the allocated memory freed as before by free(). All bytes in memory allocated by calloc() are cleared to zero, whereas memory allocated by malloc() is left unchanged. The description for calloc() is:

Example:
          void * ptr;         /* pointer to allocated block of memory */
          unsigned number;    /* number of elements to allocate */
          unsigned size;      /* size of memory to allocate in bytes */

ptr = calloc(number, size);

We could have used calloc() in the previous program example as follows:

p = (struct stdrec *)calloc(n, sizeof(struct stdrec));
We could have then used the fact that the allocated memory is set to zero to signal the end of the number of elements in the effective array.

Normally, an array is defined with the range for each dimension specified, and memory is allocated at compile time. As we saw above, a single dimensional array of a desired size can be effectively defined at run time, i.e. during execution, using dynamic allocation. It is equally easy to define multi-dimensional arrays during execution by using dynamic allocation.

We first allocate an appropriate block of memory for the two dimensional array size desired. Since array storage in C is in row major form, we then treat the block as a sequence of rows with the desired number of columns. The pointer to the allocated block is a pointer to the base type of the array; therefore, it must be incremented to access the next column in a given row. It must also be incremented to move from the last column of a row to the first column of the next row.

Figure 14.16 shows an example that asks the user to specify the number of rows and columns for a two dimensional array. It then dynamically allocates a block of memory to accommodate the array. The block is then treated as a two dimensional array with the specified rows and columns. Data is read into the array, and then the array is printed.

A sample output is shown below:



Previous: 14.2.1 Library Functions for Dynamic Allocation
Up: 14.2 Dynamic Memory Allocation
Previous Page: 14.2.1 Library Functions for Dynamic Allocation
Next Page: 14.3 Pointers to Functions

tep@wiliki.eng.hawaii.edu
Sat Sep 3 07:21:51 HST 1994