728x90

구조체(struct)는 하나 이상의 변수를 그룹 지어서 새로운 자료형을 정의하는 것이다.

중첩 구조체란 다른 구조체를 멤버로 포함하는 구조체이다.


예제 1

#define _CRT_SECURE_NO_WARNINGS // strcpy 보안 경고로 인한 컴파일 에러 방지
#include <stdio.h>
#include <string.h>  // strcpy 함수가 선언된 헤더 파일

struct Phone {
    int areacode;
    unsigned long long number;
};

struct Person {
    char name[20];
    int age;
    char address[100];
    struct Phone phone;
};

int main() {
    Person p1;

    strcpy(p1.name, "홍길동"); //p1.name = "홍길동"; 로 입력하면 에러 발생함.
    p1.age = 30;
    strcpy(p1.address, "서울시 관악구 조원중앙로");
    p1.phone.areacode = 82;
    p1.phone.number = 1012345678;

    printf("성명 : %s\n", p1.name);
    printf("나이 : %d\n", p1.age);
    printf("주소 : %s\n", p1.address);
    printf("%d %llu\n", p1.phone.areacode, p1.phone.number);
    // %llu : unsigned long long 변수를 출력할 때 사용
    // %lld : signed long long 변수를 출력할 때 사용

} 


예제2

#include <stdio.h>
#include <string.h>

struct college_detail {
    int college_id;
    char college_name[50];
};

typedef struct {
    int id;
    char name[20];
    float percentage;
    // structure within structure
    struct college_detail clg_data;
}Student_Data; // 구조체 별칭

int main() {

    Student_Data stu_data = { 1, "홍길동", 89.5, 71145, "OO대학교" };
    Student_Data *stu_data_ptr = &stu_data; // 구조체 포인터 선언

    printf(" Id : %d \n", stu_data_ptr->id);
    printf(" 성명 : %s \n", stu_data_ptr->name);
    printf(" 퍼센트 : %f \n\n", stu_data_ptr->percentage);

    printf(" 대학교 Id : %d \n",    stu_data_ptr->clg_data.college_id);
    printf(" 대학교 : %s \n", stu_data_ptr->clg_data.college_name);

    return 0;
}


구조체 선언을 아래와 같이 해도 된다.

struct college_detail {
    int college_id;
    char college_name[50];
};


struct student_detail {
    int id;
    char name[20];
    float percentage;
    // structure within structure
    struct student_college_detail clg_data;
}Student_Data, *stu_data_ptr;

struct student_detail stu_data = { 1, "홍길동", 89.5, 71145, "OO대학교" };
stu_data_ptr = &stu_data;


그리고 구조체 내부에 구조체를 넣어도 된다.

typedef struct {
    int id;
    char name[20];
    float percentage;

    struct college_detail {
        int college_id;
        char college_name[50];
    };
    struct college_detail clg_data;
}Student_Data; // 구조체 별칭


블로그 이미지

Link2Me

,