Tech News
← Back to articles

Writing memory efficient C structs

read original related products more articles

29 July 2025

Writing memory efficient C structs

by Tom Scheers

A struct in C is the best way to organize your data so that you can easily use the data later in your program. However, there are a few caveats to C structures, mainly how their memory works.

Our struct

struct Monster { bool is_alive ; // Used to see whether or not the monster is alive int health ; // Health of the monster int damage_hit ; // Damage they deal per hit char name [ 64 ]; // Name of the monster with a max of 63 characters and one \0, 64 bytes allocated to the stack float x_position ; // The x_position of the monster in the game float y_position ; // The y_position of the monster in the game bool can_fly ; // Boolean whether or not monster can fly bool can_swim ; // Boolean whether or not monster can swim int speed ; // Speed of monster whilst walking bool is_poisoned ; // If the monster is poisoned bool has_armor ; // If the monster has any protection };

Here I’ve defined a basic Monster struct. It has a lot of basic fields which hold some data about this monster. Before trying to reduce the size of this struct we should probably look at how large this struct is at the moment. So let’s count all of the bytes!

struct Monster { bool is_alive ; // Boolean is 1 byte int health ; // Int is 4 bytes int damage_hit ; // 4 bytes char name [ 64 ]; // 64 times char, which is 1 byte each; 64 bytes total float x_position ; // Float is 4 bytes float y_position ; // 4 bytes bool can_fly ; // 1 byte bool can_swim ; // 1 byte int speed ; // 4 bytes bool is_poisoned ; // 1 byte bool has_armor ; // 1 byte };

So let’s see, we have 5 Booleans, 3 integers, 2 floats and one 64 byte string… That should be 90 bytes! Let’s test this theory:

sizeof ( struct Monster ); // => 96

... continue reading