Understanding Structures and Padding in C

Last updated on Feb 01,2021 33.5K Views


Definition of Structures in C:

Structure is a collection of multiple variables of different types. Structures are used to create user-defined data types as a collection of other data types. For example, the co-ordination of location on earth consists of latitude and longitude. Let’s look at the syntax for this;

Struct coord{
Float latitude;
Char lat_direction;
Float longitude;
Float long_direction;
};

The above syntax declares a new user-defined data type ‘struct coord’ which can be used to store the co-ordinates.

Examples of Using Structures:

#include<stdio.h>
struct name {
char fname[50];
char lname[50];
};
int main()
{
struct name student;
printf(“Enter your first name:”);
gets(student.fname);
printf(“Enter your last name:”);
gets(student.lname);
printf(“First Name:%s
”,student.fname);
printf(“Last Name:%s
”, student.lname);
system(“PAUSE”);
Return 0;
}

Let’s compile and run the program.

Enter the first name and the last name. The output will be as shown below:

Structures and Padding in C

Structure Padding in C:

Many processors expect memory for variables to be aligned based on the size of the variable. A ‘char’ of 1 byte can be allocated anywhere in memory like 0x5000 or 0x5001. And an ‘int’ of 4 bytes, must start at a 4-byte boundary like 0x5004 or 0x5008. The structure padding is automatically done by the compiler to make sure all its members are byte aligned.

The size of the below structure is 16 bytes due to structure padding:

Struct dummy {
Char ch;
Int num;
Double temp;
}

Here ‘char’ is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary.  For ‘int’ and ‘double’, it takes up 4 and 8 bytes respectively.

Structures and Padding in C

The compiler used the 3 wasted bytes (marked in red) to pad the structure so that all the other members are byte aligned. Now, the size of the structure is 4 + 1 +3 = 8 bytes. The size of the entire structure is 8 bytes.  On knowing the structured padding, it is easier to redesign or rewrite the structure.

Let’s look at another example where the syntax is slightly different;

Structures and Padding in C

#include<stdio.h>
Struct dummy {
Int num;
Double x;
Float f;
};
Struct dummy1 {
Double x;
Int num;
Float f;
};
Int main()
{
Printf(“size:%d %d
”, sizeof(struct dummy ), sizeof(struct dummy1));
System(“PAUSE”);
Return 0;
}

The output will be as shown below;

C Structures - EdurekaGot a question for us? Please mention them in the comments section and we will get back to you.

Related Posts:

Pointers in C

Introduction to C Programming – Algorithms

Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.