User Tools

Site Tools


notes:notes:discrete:fall2023:projects:ttb0

TTB0

STRUCT

A structure is an always-public class. For this project, we'll be using one to group together the code we need for our Breakout brick.

Format the code similarly to a class:

struct Brick {
    int positionX;
    int positionY;
    ...
};

Remember that for structures, a semicolon is needed after the closing curly brace. You'll get an error otherwise.

POINTERS

MALLOC

Malloc, short for “memory allocation,” does what it says on the tin.

Malloc is used to allocate memory for specific purposes. For breakout, since we'll know how many bricks are going into our brick field, we'll use an array. An array is always the same size, which means the amount of memory used for the array will remain constant. Malloc is perfect for this scenario.

When the malloc() function is called, it sends a request to the heap in the form of a memory block (heap is memory allocated for each program). The heap's available memory must be at least equivalent to the memory block size. In this case, it will assign the malloc() that memory size function against its request. If the heap has no memory, null value is returned. The memory block is cleared using the free() function to free up the memory for other program instructions.

MALLOC’ED ARRAY

For Breakout, we need to allocate the amount of memory needed to hold our entire brick field (AKA the array of brick structs). We do that by using the sizeof function:

BrickArray = ( [Brick structure]* ) malloc( sizeof( [Brick structure] ) * [Number of bricks] );

ACCESSING WITH POINTER ARITHMETIC

In the example above BrickArray is the name of our array of brick structures. To access an individual point in the array, we'll need to use pointer arithmetic.

The position in the array will be notated as an addition to the brick array, so the following code looks at the 3rd position in the array:

BrickArray+3

In order to access the brick structure's individual variables however, we need to dereference the array. Instead of looking at the memory of the 3rd position of the array, we now look at the data stored at it:

*( BrickArray+3 )

With an additional set of parentheses, we'll be ready to access any variable of the brick structure like you would for any member of a class:

(*( BrickArray+3 )).positionX

MALLOC’ED ARRAY OF STRUCTS

notes/notes/discrete/fall2023/projects/ttb0.txt · Last modified: 2023/09/14 03:50 by 127.0.0.1