An Example of How to use the Heap


#1

Here is an example of how to use the heap after you allocate some bytes. This is the example they use in the book, but fail to show you how to use it. In the example below, I allocate 10 floats on the heap, startOfBuffer points to these 10 locations. Once you allocate the memory, you can treat the pointer similar to an array because the memory you allocate is contiguous. Then I use a for loop to print the values that the pointer points to on the heap. The syntax is exactly the same as you would with an array of floats.

int main()
{
    // Declare a float pointer
    float *startOfBuffer;

    // Ask to use some bytes from the heap. 10 floats
    startOfBuffer = (float *) malloc(10 * sizeof(float));

    for (int i = 0; i < 10; i++)
    {
        // Populate the buffer with 10 values i * 2, that startOfBuffer variable points to
        startOfBuffer[i] = i * 2;

        // Display the values using array notation []
        printf("Using array notation: startOfBuffer[%d] value is: %.0f\n",
               i, startOfBuffer[i]);

        // Display the values using pointer arithmetic
        printf("Using pointer notation: startOfBuffer[%d] value is: %.0f\n",
               i, *(startOfBuffer + i));
    }

    free(startOfBuffer);
    startOfBuffer = NULL;
    return 0;
}