공부/C언어, C++

[C언어/C++] struct 어떻게 쓰는거지? 구조체(struct) 간단 비교 예제

이니셜P 2023. 3. 16. 18:58
반응형

학생 3명의 이름과 국어, 수학, 영어 점수를 가지고 있는 데이터를 구성한다고 하자

구조체(struct)를 아직 배우지 않았다면 오른쪽 예제 처럼구성을 했을 것이다.

하지만 구조체로 데이터를 구성한다면 왼쪽 예제처럼 구성할 수 있다.

 

지금 당장 보면 코드도 더 많아져서 오른쪽 예제가 더 낫지 않나 싶을 건데 나중에 포인터와 데이터 구조를 배우게 되면 구조체 더 나아가 클래스(class)로 데이터를 구성하는 쪽이 더 유리하다.

 


no_struct.c

#include <stdio.h>

int main()
{
    char student_1_name[10] = "김철수";
    int student_1_korean = 80;
    int student_1_math = 90;
    int student_1_english = 70;

    char student_2_name[10] = "김영희";
    int student_2_korean = 95;
    int student_2_math = 75;
    int student_2_english = 60;

    char student_3_name[10] = "박민석";
    int student_3_korean = 65;
    int student_3_math = 75;
    int student_3_english = 70;

    /* . . . */

    return 0;
}

 


struct.c

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

typedef struct _Student
{
    char name[10];
    int korean;
    int math;
    int english;
} Student;

int main()
{
    Student student_1;

    strcpy(student_1.name, "김철수");
    student_1.korean = 80;
    student_1.math = 90;
    student_1.english = 70;

    Student student_2;

    strcpy(student_2.name, "김영희");
    student_2.korean = 95;
    student_2.math = 75;
    student_2.english = 60;

    Student student_3;

    strcpy(student_3.name, "박민석");
    student_3.korean = 65;
    student_3.math = 75;
    student_3.english = 70;

    /* . . . */

    return 0;
}

 

반응형