반응형
공용체(Union)는 새로운 자료형을 선언한 뒤 해당 자료형에 멤버를 담아 사용하며, 보유한 멤버들 중 크기가 가장 큰 변수의 메모리 공간을 공유한다.
#include<stdio.h>
struct student1{ // 구조체 선언
int id;
double score;
};
union student2{ // 공용체 선언
int id;
double score;
};
int main(){
struct student1 str_stu = {123, 89.5};
union student2 uni_stu = {456};
printf("구조체 크기 : %d, 유니온 크기 : %d\n\n", sizeof(str_stu), sizeof(uni_stu));
printf("구조체 id 주소 : %p, score 주소 : %p\n", &str_stu.id, &str_stu.score);
printf("유니온 id 주소 : %p, score 주소 : %p\n\n", &uni_stu.id, &uni_stu.score);
printf("구조제 id : %d\n", str_stu.id);
printf("구조체 score : %.2lf\n", str_stu.score);
printf("공용체 id : %d\n", uni_stu.id);
printf("공용체 score : %.2lf\n\n", uni_stu.score);
uni_stu.score = 99.9; // union에서 크기가 가장 큰 변수의 값을 변경하면, 나머지 멤버 변수들에 저장된 값들이 깨지게 된다.
printf("구조제 id : %d\n", str_stu.id);
printf("구조체 score : %.2lf\n", str_stu.score);
printf("공용체 id : %d\n", uni_stu.id);
printf("공용체 score : %.2lf\n", uni_stu.score);
return 0;
}
반면, 구조체는 가장 큰 크기의 배수로 결정된다. 즉, 위와 같이 멤버 변수 2개를 가지고 있는 구조체 변수 'str_stu'는 int형(4byte)과 double형(8byte)을 각 한 개씩 보유하고 있을 때 크기가 더 큰 double형 8byte × 2개로 구조체의 크기가 결정된다.
반응형
'C' 카테고리의 다른 글
[C언어] 실습: '0' 입력할 때까지 정수를 입력받는 프로그램 구현하기 (0) | 2021.06.14 |
---|---|
[C언어] 열거형 (Enumeration) (0) | 2021.06.11 |
[C언어] 실습: 헤더 파일 및 C 파일 만들기 (0) | 2021.06.09 |
[C언어] 실습: 배열에 저장된 정수의 합 출력하기 (0) | 2021.06.08 |
[C언어] time(NULL) (0) | 2021.06.07 |