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

(Romina) #1

satisfy your allocation request):



  1. Allocates the number of bytes you request and makes sure no other program can overwrite that
    memory until your program frees it

  2. Assigns your pointer to the first allocated value


Figure 26.2 shows the result of the previous temperature malloc() function call. As you can see
from the figure, the heap of memory (shown here as just that, a heap) now contains a fenced-off area
of 10 integers, and the integer pointer variable named temps points to the first integer. Subsequent
malloc() function calls will go to other parts of the heap and will not tread on the allocated 10
integers.


FIGURE 26.2 After allocating the 10 integers.

What do you do with the 10 integers you just allocated? Treat them like an array! You can store data
by referring to temps[0], temps[1], and so on. You know from the last chapter that you access
contiguous memory using array notation, even if that memory begins with a pointer. Also remember
that each set of allocated memory will be contiguous, so the 10 integers will follow each other just as
if you allocated temps as a 10-integer array.


The malloc() allocation still has one slight problem. We still have to explain the left portion of the
temperature malloc(). What is the (int *) for?


The (int *) is a typecast. You’ve seen other kinds of typecasts in this book. To convert a float
value to an int, you place (int) before the floating-point value, like this:


aVal = (int)salary;

The * inside a typecast means that the typecast is a pointer typecast. malloc() always returns a
character pointer. If you want to use malloc() to allocate integers, floating points, or any kind of
data other than char, you have to typecast the malloc() so that the pointer variable that receives
the allocation (such as temps) receives the correct pointer data type. temps is an integer pointer;
you should not assign temps to malloc()’s allocated memory unless you typecast malloc()
into an integer pointer. Therefore, the left side of the previous malloc() simply tells malloc()
that an integer pointer, not the default character pointer, will point to the first of the allocated values.


Note
Free download pdf