sizeof of a structure
The size of a structure in C is the sum of the sizes of its members. The size of a structure type can be determined using the sizeof operator in C.
In this article, we have to do one small experiment.
Let’s use the sizeof operator to find out the total memory consumed by our structure variables in this case.
I want to find out the memory consumed by carBMW. For that, I use the sizeof operator. Let’s print that.
printf(“Sizeof of struct carModel is %I64u\n”, sizeof(struct carModel));
Here I use sizeof. You can mention carBMW this variable itself here or you can mention struct carModel this data type.
First, let’s calculate theoretically how much memory it would consume. As I said, it would consume around 14 bytes. Let’s verify that.
Let’s execute, and it says that it consumes 16 bytes, as shown in Figure 2. It is showing 2 bytes more. That’s because of structure padding.
Most of the time, you programmer need not worry about structure padding. But, if you are really curious about what’s happening behind the scene, we should dig into the details of how exactly the compiler generates instructions to store our member elements in the memory.
What if I have used only one member element in this structure?
uint8_t carSpeed; only one member element, and let’s check.
It consumes 1 byte, as shown in Figure 3.
What if I have used uint32 here?
uint32_t carPrice. So, your guess maybe it may consume 4 + 1 = 5, or 6.
Let’s see how much it consumes. It consumes 8 bytes, as shown in Figure 4.
So, let’s investigate why it happens like that. The reason for that is data alignment. We’ll discuss this in the following article.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1