

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Memory
incomplete
2: What Is an Address?
incomplete
3: Virtual Memory
incomplete
4: Pointers
incomplete
5: Why Pointers?
incomplete
6: Pointer Basics
incomplete
7: Pointers to Structs
incomplete
8: C Arrays
incomplete
9: Arrays As Pointers in C
incomplete
10: Multibyte Arrays
incomplete
11: Array Casting
incomplete
12: Pointer Size
incomplete
13: Arrays Decay to Pointers
incomplete
14: C Strings
incomplete
15: C String Library
incomplete
16: Forward Declaration
incomplete
17: Mutual Structs
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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
*/
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.