sizeof for a struct in c language

The sizeof for a struct 
	is not always equal to the sum of sizeof of each individual member. 
This is because of the padding added by the compiler 
	to avoid alignment issues. 
Padding is only added 
	when a structure member is followed by a member with a larger size 
	or at the end of the structure.

Different compilers might have different alignment constraints 
	as C standards state that 
		alignment of structure totally depends on the implementation.
// C program to illustrate
// size of struct
#include 

int main()
{

	struct A {

		// sizeof(int) = 4
		int x;
		// Padding of 4 bytes

		// sizeof(double) = 8
		double z;

		// sizeof(short int) = 2
		short int y;
		// Padding of 6 bytes
	};

	printf("Size of struct: %ld", sizeof(struct A));

	return 0;
}

sizeof for a struct in c language_第1张图片

// C program to illustrate
// size of struct
#include 

int main()
{

	struct B {
		// sizeof(double) = 8
		double z;

		// sizeof(int) = 4
		int x;

		// sizeof(short int) = 2
		short int y;
		// Padding of 2 bytes
	};

	printf("Size of struct: %ld", sizeof(struct B));

	return 0;
}

sizeof for a struct in c language_第2张图片

// C program to illustrate
// size of struct
#include 

int main()
{

	struct C {
		// sizeof(double) = 8
		double z;

		// sizeof(short int) = 2
		short int y;
		// Padding of 2 bytes

		// sizeof(int) = 4
		int x;
	};

	printf("Size of struct: %ld", sizeof(struct C));

	return 0;
}

sizeof for a struct in c language_第3张图片

你可能感兴趣的:(c语言,开发语言)