#include <stdio.h>
#include <string.h>
// typedef : 형 재선언
// 형재선언을 하면 구조체를 선언 및 정의를 할때 앞에 struct를 생략할수 있다.
// 구조체에서 왼쪽 피연사자가 포인터 변수이면 -> 를 사용하여 값을 대입해야한다.
#pragma pack(push,1) // 현재 맞춤 정보를 1Byte 단위로 설정
typedef struct MYData {
char ch;
int nAge;
double dData;
} MYData;
typedef struct UserData {
char ch;
int nAge;
}UserData;
#pragma pack(pop) // 맞춤 정보 설정 해제
void GetUserData(UserData *pUser) {
////%*c는 \n을 제거하기 위한것
//scanf("%d%*c", &pUser->nAge);
//gets_s(pUser->szName, sizeof(pUser->szName));
//gets_s(pUser->szPhone, sizeof(pUser->szPhone));
}
int main(void) {
printf("%d\n", sizeof(UserData));
printf("%d\n", sizeof(MYData));
return 0;
}
바이트 단위가 아닌 비트 단위 데이터로 다루는 방법
#include <stdio.h>
#include <string.h>
// typedef : 형 재선언
// 형재선언을 하면 구조체를 선언 및 정의를 할때 앞에 struct를 생략할수 있다.
// 구조체에서 왼쪽 피연사자가 포인터 변수이면 -> 를 사용하여 값을 대입해야한다.
typedef struct DataFlag
{
unsigned char main : 1; // 8 비트 중 오른쪽 1비트
unsigned char left : 2; // 오른쪽 2~3번째 비트
unsigned char right : 3; // 오른쪽 4~6번째 비트
unsigned char top : 2;//오른쪽 7~8번째 비트(왼쪽 두 비트)
}DataFlag;
int main(void) {
DataFlag flagSwitch = { 0,3,7,4 };
printf("%d\n", flagSwitch.main);
printf("%d\n", flagSwitch.left);
printf("%d\n", flagSwitch.right);
printf("%d\n", flagSwitch.top);
printf("%X\n", *(unsigned char *)&flagSwitch);
printf("%d\n", sizeof(flagSwitch));
return 0;
}
출력 결과
