๐๊ตฌ์กฐ์ฒด(struct)
์ฌ์ฉ์ ์ ์ธ ํ์ . ํ๋ ์ด์์ ๋ณ์๋ฅผ ํ๋๋ก ๋ฌถ์ด ์๋ก์ด ์๋ฃํ์ ๋ง๋๋ ๊ฒ.
ํฌ์ธํฐ ๋ณ์๋ ๋ฐฐ์ด๋ ๋ฉค๋ฒ๋ก ๊ฐ์ง ์ ์๋ค. ํฌ์ธํฐ๋ก ๊ตฌ์กฐ์ฒด๋ฅผ ์ฐธ์กฐํ ์ ์๋ค.
#include <stdio.h>
struct Student {
char name[100];
int age, height;
}
int main(){
struct Student student;
printf("์ด๋ฆ์ ์
๋ ฅํ์ธ์: ");
scanf_s("%s", &student.name, sizeof(student.name));
printf("๋์ด๋ฅผ ์
๋ ฅํ์ธ์: ");
scanf_s("%d", &student.age);
printf("ํค๋ฅผ ์
๋ ฅํ์ธ์(cm): ");
scanf_s("%d", &student.height);
printf("[์
๋ ฅ ์ ๋ณด] ์ด๋ฆ: %s, ๋์ด: %d์ธ, ํค: %dcm\n", student.name, student.age, student.height);
return 0;
}
๊ตฌ์กฐ์ฒด ์ด๊ธฐํ
#include <stdio.h>
struct Student {
int number;
char name[10];
char grade;
};
int main() {
struct Student s1 = { 123456, "Kim", 'A' };
return 0;
}
๐๊ตฌ์กฐ์ฒด ํฌ์ธํฐ
ํฌ์ธํฐ๋ก ๊ตฌ์กฐ์ฒด์ ์ ๊ทผํ ๊ฒฝ์ฐ ๊ฐ์ ๋ฉค๋ฒ ์ฐธ์กฐ ์ฐ์ฐ์(->)๋ฅผ ์ฌ์ฉํ๋ค.
#include <stdio.h>
struct student {
char name[100];
int age, height;
}st1[3] = {
{"lch", 25, 178},
{"kim", 30, 160},
{"park", 40, 180}
};
int main() {
student* pSt = st1;
for (int i = 0; i < sizeof(st1) / sizeof(st1[0]); i++) {
printf("์ด๋ฆ: %s, ๋์ด: %d, ํค: %d\n", (pSt + i)->name, (pSt + i)->age, (pSt + i)->height);
}
return 0;
}
๐๊ตฌ์กฐ์ฒด ๋ฉ๋ชจ๋ฆฌ ํ ๋น ๋ฐฉ์
struct student {
char grade;
int num, score;
}
์์ ๊ฐ์ ๊ตฌ์กฐ์ฒด๊ฐ ์๋ค๊ณ ํ์ ๋, ๊ฐ๊ฐ์ ๋ฉค๋ฒ๊ฐ `grade` 1byte, `num`๊ณผ `score`๊ฐ 4byte์ฉ ๊ฐ๊ฐ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ฐ์ง๋ค.
* ์ด๋ CPU๊ฐ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ฝ์ ๋ ํ ๋ฒ์ ์ฝ์ ์ ์๋๋ก ์ปดํ์ผ๋ฌ๊ฐ ๋ฐ์ดํธ๋ฅผ ์ต์ ํ(ํจ๋ฉ)ํด์ฃผ๋ ๊ณผ์ ์ ๊ฑฐ์น๋ค. ๊ตฌ์กฐ์ฒด๋ฅผ ๊ตฌ์ฑํ๋ ๋ฉค๋ฒ ์ค ๊ฐ์ฅ ํฌ๊ธฐ๊ฐ ํฐ ๋ฉค๋ฒ์ ์๋ฃํ์ ๋ฐฐ์๊ฐ ๋๋๋ก ์ ๋ ฌํ๋ค.
๐๊ณต์ฉ์ฒด(union)
๊ตฌ์กฐ์ฒด์ ๋ง์ฐฌ๊ฐ์ง๋ก ์ฌ์ฉ์ ์ ์ ํ์ (์๋ฃํ)์ผ๋ก, ์ฌ๋ฌ ๊ฐ์ ๋ฉค๋ฒ๋ก ํ๋์ ์๋ก์ด ์๋ฃํ์ ๋ง๋ ๋ค. ๋จ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ณต์ ํ๋ค๋ ๊ฒ์ ์ฐจ์ด์ ์ผ๋ก ๊ฐ์ง๋ค.(๊ฐ์ฅ ํฐ ๋ฉค๋ฒ ๋ณ์์ ๋ฉ๋ชจ๋ฆฌ ํฌ๊ธฐ๋ฅผ ๊ณต์ ํ๋ค.)
๊ฐ์ด ๋ณด์กด๋์ง ์๋๋ค. ๋ค๋ฅธ ๋ฉค๋ฒ๋ฅผ ์ฌ์ฉํ๊ฒ ๋๋ฉด ๊ฐ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ฎ์ด์ฐ๊ฒ ๋๋ฏ๋ก ๋์์ ์ฌ์ฉํ์ง ์๋๋ก ์ฃผ์ํ๋ค.
๋ฉ๋ชจ๋ฆฌ๋ฅผ ์๋ผ๊ธฐ ์ํด ์ฌ์ฉํ๋ค.
union unTemp {
char a;
int b;
double c;
}un;
int main() {
un.a = 'A';
printf("๋ฌธ์ํ a: %c\n", un.a);
un.b = 100;
printf("์ ์ํ b: %d\n", un.b);
un.c = 3.14;
printf("์ค์ํ c: %.2f\n", un.c);
printf("๋ฌธ์ํ a: %c\n", un.a);
printf("์ ์ํ b: %d\n", un.b);
printf("์ค์ํ c: %.2f\n", un.c);
printf("%x %x %x", &un.a, &un.b, &un.c);
return 0;
}
๋ฌธ์ํ a: A
์ ์ํ b: 100
์ค์ํ c: 3.14
๋ฌธ์ํ a:
์ ์ํ b: 1374389535
์ค์ํ c: 3.14
๋ฉ๋ชจ๋ฆฌ ์ฃผ์๊ฐ: a: 9d23d1c0, b: 9d23d1c0, c: 9d23d1c0
๐์ฐธ๊ณ
๊ตฌ์กฐ์ฒด์ ๋ฉ๋ชจ๋ฆฌ ์ ์ฅ๋ฐฉ์
๊ตฌ์กฐ์ฒด์ ๋ฉ๋ชจ๋ฆฌ ์ ์ฅ๋ฐฉ์์ ์๋ฉด ๋ฉค๋ฒ๋ณ์๋ค์ ์ ์ธํ ๋ ์ข ๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ํจ์จ์ , ์ต์ ํ๋๊ฒ ์ธ ์ ์๋ค.1. ๊ตฌ์กฐ์ฒด์ ๋ฐ์ดํธ ํจ๋ฉ๋ฐ์ดํธํจ๋ฉ์ด๋ ๋ฉค๋ฒ ๋ณ์๋ฅผ ๋ฉ๋ชจ๋ฆฌ์์ CPU๋ก ์ฝ์ ๋ ํ๋ฒ์
sjh836.tistory.com
[C++] Union (๊ณต์ฉ์ฒด)
๊ณต์ฉ์ฒด(union)๋ ๊ตฌ์กฐ์ฒด(struct)์ ๊ฑฐ์ ๋์ผํ์ง๋ง ๋ชจ๋ ๋ฉค๋ฒ ๋ณ์๊ฐ ํ๋์ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ๊ณต์ ํ๋ค๋ ์ ์ด ๋ค๋ฆ ๋๋ค.
velog.io
'C, C++' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++] ์์(Inheritance) (0) | 2024.08.29 |
---|---|
[C++] ๊ฐ์ฒด ์งํฅ (6) | 2024.08.19 |
[C] ๋์ ๋ฉ๋ชจ๋ฆฌ ํ ๋น (0) | 2024.08.13 |
[C] C์ธ์ด ๊ธฐ์ด (0) | 2024.08.09 |
[C++] ๊ธฐ์ด (0) | 2023.08.25 |