Microcontroller Embedded C Programming Lecture 146| Sizeof of a structure

  • Post author:
  • Post category:Blog

 

 

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.

Figure 1. Code
Figure 1. Code

 

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.

https://www.traditionrolex.com/24
Sizeof of a structure
Figure 2. Output

 

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. 

Sizeof of a structure
Figure 3. Example

 

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. 

Sizeof of a structure
Figure 4. Example

 

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

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.