C Programming

How do I Calculate the Value of sizeof(struct) in C?

In computing, the keyword or operator referred to as “sizeof” can be used to identify how much memory is allocated for a particular data type or variable. To calculate the amount of space of the structures, the sizeof() method can be utilized. In this guide, we will first look at how to determine the size of a struct in C and also see its modifiers with example programs.

How can I Determine the size of a struct in C?

The sizeof() function in the C programming language is used to calculate the total number of bytes allocated by the data type and variable. In C, a structure’s size is equal to the total size of each of its constituent parts, with any extra padding that might be necessary for alignment reasons.

Syntax

The sizeof() in C can be used to calculate a struct’s size in bytes. The following syntax is used to calculate the size of a struct value:

sizeof(struct struct_Name);

Change struct_Name to the struct name whose size you want to determine.

Let’s determine the total size of the structure with the following structural definition:

struct Person {
    char first_name[20];
    char second_name[20];
    int my_age;
    float result;
};

Four members make up the Person structure: first_name, second_name, my_age, and result. The first_name and second_name members each have a size of 40 bytes, while the age member and result have a size of 4 bytes. The my_Person struct would therefore have a total size of 48 bytes.

Example to Calculate the sizeof() the Structure in C

In C, all you have to do is pair the structure’s name with the sizeof operator to determine the size of the struct. The size of the Person structure, for instance, would be printed using the following code:

#include <stdio.h>

struct Person {
    char first_name[20];
    char second_name[20];
    int my_age;
    float result;
};
int main() {
    printf("Total Size of structure: %d bytes\n", sizeof(struct Person));
    return 0;
}

The above example is displayed in the below output:

Note: It’s crucial to remember that if a structure includes any padding bytes, its true size can end up being greater than the total of its parts. To make sure that a structure’s members are aligned on particular memory bounds, padding is added.

Conclusion

In, computing the size of a struct can be determined by applying the sizeof operator and the structure’s name. However, it’s crucial to keep in mind that due to padding supplied for alignment purposes, a structure’s actual size may be greater than the sum of its parts.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.