#include <stdio.h>


typedef float HP;
typedef float MP;
typedef int EXP;
typedef int LV;
typedef int GOLD; //자료형을 재정의

struct SCharacter { 
// 구조체 멤버 변수(Structure Member Variables)
// 구조체 패딩 (Structure Padding)
// 순서에 따른 메모리에 빈공간이 생김 그걸 패딩이라고 부름
// 바이트 크기가 큰걸 위쪽에 두면 메모리 낭비가 적어짐
LV lv;
HP hp;
MP mp;
EXP exp;
};
typedef struct SCharacter SCharacter;
//재정의 밑에껄 자주씀

typedef struct _SEnemy {
LV lv;
GOLD gold;
} SEnemy; // 재정의 같이한것 (자주씀)

// 공용체(Union)
union UMemory {
char c;
int i;
double d;
}UMemory;

 

int main() {

// 구조체(Structure)
// 사용자정의 자료형
struct SCharacter player = {10 , 3.14f};
// .<- 구조체 멤버 접근 지정자(연산자)

player.lv = 10;

 

printf("player. lv: %d\n", player.lv); //구조체 기본 사용법

	printf("struct SCharcter Size: %d Byte\n", sizeof(struct SCharacter));

	printf("player. lv: %d (%p)\n", player.lv, &player.lv);
	printf("player. Hp: %f (%p)\n", player.hp, &player.hp);
	printf("player. mp: %f (%p)\n", player.mp, &player.mp);
	printf("player.exp: %d (%p)\n", player.exp, &player.exp);
	//배열처럼 정렬되어있다. 패딩이 발생하는 원인

	printf("\n");
	SEnemy* pEnemy = (SEnemy*)malloc(sizeof(SEnemy));
	// <- 포인트 멤버 접근 지정자(연산자)
	// 포인터로 만들어진 멤버에 접근할때 사용
	pEnemy->gold = 1000;
	printf("pEnemy->gold: %d\n", pEnemy->gold);


	if (pEnemy != NULL) {
		free(pEnemy);
		pEnemy = NULL;
	}

	printf("\n");

	SCharacter copyPlayer = player;
	copyPlayer.lv = 100;
	printf("copyPlayer.lv: %d\n", copyPlayer.lv);
	printf("copyPlayer.mp: %f\n", copyPlayer.mp);
	printf("player.lv: %d\n", player.lv);

	printf("\n");
	printf("union UMemory Size: %d Byte\n", sizeof(UMemory));

	union UMemory mem;
	mem.c = 'a';
	printf("mem.c : %c\n", mem.c);
	mem.d = 3.14;
	printf("mem.d: %lf\n", mem.d);

	return 0;
}

 

+ Recent posts