We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Array Casting

Let's explore a special kind of psychopathy that's possible in C. Let's assume we have this array of 3 structs where each struct holds 3 integers:

coordinate_t points[3] = {
  {5, 4, 1},
  {7, 3, 2},
  {9, 6, 8}
};

Because arrays are basically just pointers (in most cases; more on that later), and we know that structs are contiguous in memory, we can cast the array of structs to an array of integers:

int *points_start = (int *)points;

The cast tells C to treat the same starting address as an int *, so each index walks one int at a time through the contiguous struct fields.

Then we can iterate over the known number of integers in the array of structs:

for (int i = 0; i < 9; i++) {
  printf("points_start[%d] = %d\n", i, points_start[i]);
}
/*
points_start[0] = 5
points_start[1] = 4
points_start[2] = 1
points_start[3] = 7
points_start[4] = 3
points_start[5] = 2
points_start[6] = 9
points_start[7] = 6
points_start[8] = 8
*/

Assignment

Take a look at the dump_graphics function. It works similarly to the example above.

Go ahead and run it in its current state. You should notice that after all the values specified in main.c are printed... all hell breaks loose. That's because we've ventured out of the bounds of our array! We're going rogue! We're in the weeds! We're in undefined territory. This is something you do not want to do. It's one of the things that makes C powerful but dangerous. Other languages stop you from going out of bounds, but C will let you fly off the edge of the world.

Fix the loop to only print the values that are actually in the array of structs. Take a look at the graphics_t struct in exercise.h to figure out how large each struct is.