728x90
구조체란?
- 구조체는 사용자 정의 자료형(User-defined data type)을 만들 수 있도록 지원하는 기능입니다.
- 기본 자료형(int, float 등)과 달리, 사용자가 직접 새로운 자료형을 정의할 수 있습니다.
- 구조체도 다른 구조체를 포함하여 확장할 수 있습니다.
typedef: 타입 재정의
- typedef를 사용하면 복잡한 구조체 타입을 새로운 이름으로 정의할 수 있습니다.
- 이를 통해 코드 가독성을 높이고, 구조체를 더 쉽게 사용할 수 있습니다.
기본 구조
typedef struct 구조체이름 {
타입 정의
} 사용자정의타입이름, *포인터타입이름;
예제 코드
#include <stdio.h>
#include <string.h>
// typedef를 사용한 구조체 정의
// _tagStudent는 구조체 이름, STUDENT는 사용자 정의 타입 이름
// C에서는 사용자 정의 타입(STUDENT)을 추가로 지정해야 하지만, C++에서는 구조체 이름을 그대로 사용할 수 있음
// PSTUDENT는 STUDENT 구조체의 포인터 타입 이름
typedef struct _tagStudent {
char strName[32]; // 학생 이름 (최대 31자 + NULL 문자)
int iNumber; // 학생 번호
int iKor; // 국어 점수
int iEng; // 영어 점수
int iMath; // 수학 점수
int iTotal; // 총점
float fAvg; // 평균 점수
} STUDENT, *PSTUDENT;
// _tagMyst 구조체 정의
typedef struct _tagMyst {
int a; // 정수형 변수
float f; // 실수형 변수
} MYST;
// 구조체 안에 다른 구조체를 멤버로 포함 가능
typedef struct _tagBig {
MYST k; // MYST 구조체를 멤버로 포함
int i; // 정수형 변수
char c; // 문자형 변수
} BIG;
구조체 초기화 방법
구조체를 선언한 후에는 여러 가지 방식으로 초기화할 수 있습니다.
1. 기본 초기화 (전체 0으로 초기화)
STUDENT stStudent = {}; // 모든 멤버 변수를 0 또는 기본값으로 초기화
2. 멤버 변수 순서대로 초기화
STUDENT stStudent = {"홍길동", 1001, 90, 85, 80, 255, 85.0f};
구조체 멤버 순서대로 값을 대입합니다. (C에서는 모든 멤버 값을 지정해야 합니다.)
3. 개별 멤버 변수에 직접 할당
STUDENT stStudent;
stStudent.iNumber = 1001;
stStudent.iKor = 90;
stStudent.iEng = 85;
stStudent.iMath = 80;
stStudent.iTotal = stStudent.iKor + stStudent.iEng + stStudent.iMath;
stStudent.fAvg = stStudent.iTotal / 3.0f;
구조체 변수를 선언한 후, 개별적으로 값을 할당합니다.
4. memset을 사용한 초기화 (모든 값 0으로 설정)
#include <string.h>
memset(&stStudent, 0, sizeof(STUDENT));
구조체 전체를 0으로 채울 때 유용합니다. 단, memset은 float 타입 멤버에 대해 정확한 초기화를 보장하지 않으므로 주의해야 합니다.
구조체 초기화 예제 코드
#include <stdio.h>
#include <string.h>
typedef struct _tagStudent {
char strName[32];
int iNumber;
int iKor;
int iEng;
int iMath;
int iTotal;
float fAvg;
} STUDENT;
int main() {
// 1. 전체 0 초기화
STUDENT stStudent1 = {};
// 2. 순서대로 초기화
STUDENT stStudent2 = {"김철수", 1002, 88, 92, 77, 257, 85.67f};
// 3. 개별 할당
STUDENT stStudent3;
stStudent3.iNumber = 1003;
stStudent3.iKor = 75;
stStudent3.iEng = 80;
stStudent3.iMath = 85;
stStudent3.iTotal = stStudent3.iKor + stStudent3.iEng + stStudent3.iMath;
stStudent3.fAvg = stStudent3.iTotal / 3.0f;
// 4. memset을 이용한 초기화
STUDENT stStudent4;
memset(&stStudent4, 0, sizeof(STUDENT));
// 결과 출력
printf("stStudent2: 이름=%s, 학번=%d, 국어=%d, 영어=%d, 수학=%d, 총점=%d, 평균=%.2f\n",
stStudent2.strName, stStudent2.iNumber, stStudent2.iKor, stStudent2.iEng, stStudent2.iMath, stStudent2.iTotal, stStudent2.fAvg);
return 0;
}
요약
✅ 구조체는 사용자가 직접 정의하는 자료형
✅ typedef를 사용하면 구조체 타입을 간결하게 정의 가능
✅ 구조체 내부에 다른 구조체 포함 가능 (확장성 제공)
✅ 구조체 초기화 방법
1️⃣ {}을 사용해 모든 멤버를 0으로 초기화
2️⃣ {값, 값, 값} 형태로 멤버 순서대로 초기화
3️⃣ 구조체 선언 후 개별적으로 멤버 변수에 값 할당
4️⃣ memset을 사용해 0으로 초기화 (주의 필요)
'C++ > 유튜브 어소트락 게임아카데미 C++무료강의' 카테고리의 다른 글
8. 포인터 (0) | 2025.04.15 |
---|---|
7. 지역변수, 전역변수 (0) | 2025.04.02 |
5. 배열 (0) | 2025.03.26 |
4 함수 (0) | 2025.03.26 |
3. 연산자 및 전처리 구문 (0) | 2025.03.24 |