본문 바로가기
공부,일/c언어

구조체의 padding

by fromnothing1 2021. 6. 4.

구조체를 메모리에 구현할때 는 복잡한 로직을 따라서 만든다. 

나중에 통신을 할때는 데이터만 받고 type 을 모르기 때문에 우리가 정의하는 struct 의 메모리 구조를 아는것은 

매우중요하다.

다음의 원리와 예제를 보고 이해해보자 

 

1. 차례대로 구조체의 멤버를 메모리에 저장한다.

2.  4byte 기준으로 데이터를 묶는다.

3. 4byte 로 딱 안떨어지면 다른 4byte 메모리에 저장한다. 

4. 공간이 남으면 2byte 기준으로도 넣는다. 

 

#include<stdio.h>

struct smart1 // 기본적으로 어떻게 동작하는지 
{
	char a1;
	int a;
	char a2;
};

struct smart2
{
	int a;    // 4
	short b;  // 8
	char c;    // 8
	char d;    // 8
	char e;    // 12
	short f;	//12
	char g;		//16
};

struct smart3
{
	char a1;  //4
	int a;		//8		
	char b[10]; //20
	char a2;    //20
};

#pragma pack(1) // 1byte 씩 pading 해라 
struct smart4   // #pragma 명령어로 통해서 1byte 기준 으로 데이터 저장
{
	char a1;
	int a;
	char a2;
};
#pragma pack(4)

struct smart5   // 사용안하는 bit 에 pading 을 줘서 struct 타입을 정해준다.
{
	char a1;
	char pad1[3]; // pad bytes //not use
	int a;
	char a2;
	char pad2[3]; // pad bytes //not use
};



int main()
{
	struct  smart2 test = {'b','c','d','e','f',17,'a'};

	printf("sizeof(struct smart1) : %d\n", sizeof(struct smart1));
	printf("sizeof(struct smart2) : %d\n", sizeof(struct smart2));
	printf("sizeof(struct smart3) : %d\n", sizeof(struct smart3));
	printf("sizeof(struct smart4) : %d\n", sizeof(struct smart4));
	printf("sizeof(struct smart5) : %d\n", sizeof(struct smart5));
	return 0;
}
	

 

 

이해를 돕기위해  Smart2 구조체가 어떻게 메모리에 저장되는지 설명 하겠다.

 

struct smart2
{
int a;    // 4
short b;  // 8
char c;    // 8
char d;    // 8
char e;    // 12
short f; //12
char g; //16
};

실제 메모리 저장되는 모습

f 의 경우  e 를 집어 넣은후 3byte 공간이 남아서 2byte 기준으로 1byte 를 padding bit로 사용하고 나머지 2byte 에 들어간다. 

대충 이쁘게 들어감 

 

'공부,일 > c언어' 카테고리의 다른 글

랜덤 액세스 :fseek(),ftell()  (0) 2021.06.07
파일 입출력  (0) 2021.06.06
공용체  (0) 2021.06.04
비트필드  (0) 2021.06.03
구조체  (0) 2021.06.03

댓글