// ๋ฌธ์ : ๊ตฌ์กฐ์ฒด๋ฅผ ๋์
ํด์ ์์ค์ฝ๋๋ฅผ ๊ฐ๋จํ๊ฒ ๋ฐ๊ฟ์ฃผ์ธ์.
#include "stdio.h"
typedef struct person {
int age;
char* name;
char* hometown;
char* favorite_food;
} Person;
void introduce(Person person);
void talk(Person person);
int main() {
Person person1;
person1.age = 20;
person1.name = "ํ๊ธธ๋";
person1.hometown = "ํ์";
person1.favorite_food = "๋ก๋ณถ์ด";
Person person2;
person2.age = 50;
person2.name = "์๊บฝ์ ";
person2.hometown = "ํ์";
person2.favorite_food = "๋ก๊ตญ";
introduce(person1);
talk(person1);
introduce(person2);
talk(person2);
return 0;
}
void introduce(Person person) {
printf("== ์๊ฐ ์์ ==\n");
printf("์ด๋ฆ : %s\n", person.name);
printf("๋์ด : %d์ด\n", person.age);
printf("๊ณ ํฅ : %s\n", person.hometown);
printf("== ์๊ฐ ๋ ==\n");
}
void talk(Person person) {
printf("์ด์ผ๊ธฐ ์์ : ์๋
ํ์ธ์. ์ ๋ %d์ด, %s ์
๋๋ค. ์ ๊ณ ํฅ์ธ %s ์์๋...\n", person.age, person.name, person.hometown);
}
C
๋ณต์ฌ
// ๋ฌธ์ : ๊ตฌ์กฐ์ฒด ๋ณ์์ ์ฃผ์๋ฅผ ์ด์ฉํด์ ์๋ณธ๊ฐ์ ๋ณ๊ฒฝํ๋ ํจ์๋ฅผ ๊ตฌํํด์ฃผ์ธ์.
// ์กฐ๊ฑด : ์๋์ ๊ฐ์ด ์ถ๋ ฅํ๊ฒ ํด์ฃผ์ธ์.
#include <stdio.h>
struct School {
char* name;
int birth_date;
};
// ์ด ํจ์๋ฅผ ๋ณ๊ฒฝํด์ผ ํฉ๋๋ค.
void change(struct School* s) {
(*s).name = "๋ฏธ๊ตญ์ด๋ฑํ๊ต";
(*s).birth_date = 20180717;
}
int main(void) {
// ํํธ
// int => ํ์
// temp => ๋ณ์๋ช
int temp;
// struct School => ํ์
// s1 => ๋ณ์๋ช
struct School s1;
s1.name = "ํ๊ตญ์ด๋ฑํ๊ต";
s1.birth_date = 19860404;
printf("ํ๊ต์ ์ด๋ฆ : %s\n", s1.name);
// ์ถ๋ ฅ => ํ๊ต์ ์ด๋ฆ : ํ๊ตญ์ด๋ฑํ๊ต
printf("ํ๊ต์ ์ค๋ฆฝ์ผ : %d\n", s1.birth_date);
// ์ถ๋ ฅ => ํ๊ต์ ์ค๋ฆฝ์ผ : 19860404
change(&s1); // ์ด ๋ผ์ธ์ ์์ ํด๋ ๋ฉ๋๋ค.
printf("ํ๊ต์ ์ด๋ฆ : %s\n", s1.name);
// ์ถ๋ ฅ => ํ๊ต์ ์ด๋ฆ : ๋ฏธ๊ตญ์ด๋ฑํ๊ต
printf("ํ๊ต์ ์ค๋ฆฝ์ผ : %d\n", s1.birth_date);
// ์ถ๋ ฅ => ํ๊ต์ ์ค๋ฆฝ์ผ : 20180717
return 0;
}
C
๋ณต์ฌ
โข
๊ตฌ์กฐ์ฒด๊ฐ ๋์จ ์ด์
โฆ
์ ๋ณด๋ฅผ ํ ๊ณณ์ ๋ชจ์์ ํ๋ผ๋ฏธํฐ ๋ฑ์ ๋๊ธฐ๋ ๊ฒ์ด ํจ์ฌ ํธํด์์ด๋ค.
โฆ
๊ตฌ์กฐ์ฒด == ํด๋์ค == ํด๋
โข
๋ฉ๋ชจ๋ฆฌ ํ ๋น
โฆ
typedef struct person {
int age; // 4bytes โ ์ค์ ๋ 8bytes(64bit OS์์ 8byte packing์ด๊ธฐ ๋๋ฌธ์ ํจ๋ฉ ๋นํธ๊ฐ ์ถ๊ฐ๋จ)
char* name; // 8bytes
char* hometown; // 8bytes
char* favorite_food; // 8bytes
} Person;
โฆ
์ด 28 bytes
โฆ
์ค์ ๋ ์ด 32bytes
โข
๋ฉค๋ฒ ๋ณ์ ์ ๊ทผ
โฆ
p1 โ name์ p1์ด ๊ฐ๋ฆฌํค๋ ๊ฒ์ name์ ์๋ฏธ
โช
ex)
struct Person {int age; char* name};
struct Person *p1 = malloc(sizeof(struct Person));
p1->age = 230;
C
๋ณต์ฌ
โฆ
p1.name์ p1์ด ๊ฐ์ง๊ณ ์๋ name์ ์๋ฏธ
โช
ex)
struct Person {int age; char* name} p1;
p1.name = 230;
C
๋ณต์ฌ
โข