구조체는 여러 자료형들을 묶어 하나의 자료형으로 정의할 수 있다.
구조체 예시
// struct 키워드를 사용
struct student
{
char name[50];
int age;
int height;
int weight;
};
// 구조체 변수 선언
struct student A;
// 구조체 변수 선언 및 초기화
struct student A = { "학생", 20, 175, 70 };
구조체 타입 재정의 예시
// typedef 키워드를 추가 한다.
typedef struct student
{
char name[50];
int age;
int height;
int weight;
}student; // 재정의할 이름을 중괄호 다음에 적어 준다.
int main(void)
{
// struct를 생략할 수 있다.
student A;
return 0;
}
구조체 멤버 변수에 접근하는 방법
1. 도트 연산자 ( . )
typedef struct student
{
char name[50];
int age;
int height;
int weight;
}student;
int main(void)
{
// 도트 연산자를 이용해서 접근이 가능하다.
student A;
// 문자열은 배열의 형태로 관리되기 때문에 대입이 불가
// strcpy( ) 함수를 이용해 할당한다.
strcpy_s(A.name, "학생");
A.age = 20;
A.height = 175;
A.weight = 70;
return 0;
}
2. 화살표 연산자 ( ->)
구조체 포인터를 사용하여 멤버 변수에 접근할 때 사용한다.
typedef struct student
{
char name[50];
int age;
int height;
int weight;
} student;
int main(void)
{
// 구조체 포인터 변수 A 선언 및 메모리 할당
student *A = (student*)malloc(sizeof(student));
// 문자열 할당
strcpy_s(A->name, "학생");
// 구조체 멤버 값 할당
A->age = 20;
A->height = 175;
A->weight = 70;
// 메모리 해제
free(A);
return 0;
}
구조체는 컴퓨터가 관리를 용이하게 하기 위해 가장 큰 멤버 변수의 크기에 맞춰서 메모리를 할당한다.
구조체 멤버 변수로
int
short
char
3개를 선언할 시 가장 큰 자료형인 int(4Byte) 단위로 할당하게 된다.
총 12Byte의 메모리 공간을 차지
또한 구조체를 만들고 안에 아무런 자료형을 쓰지 않은 깡통 상태이면 1Byte의 메모리를 갖는다.
'C, C++' 카테고리의 다른 글
| 16. 파일 입출력 (0) | 2023.06.07 |
|---|---|
| 15. 공용체 (0) | 2023.06.06 |
| 13. 배열 포인터 (0) | 2023.06.03 |
| 12. 다차원 배열 (0) | 2023.06.02 |
| 11. C언어 메모리 동적 할당 (0) | 2023.06.01 |