본문 바로가기

C

[C언어] 구조체 객체 복사

반응형

같은 구조체는 객체를 복사할 수 있다.

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>   // strcpy(), strcmp()

struct student {   // student 구조체 선언
    int id;
    char name[20];
    int score;
};

int main() {

    struct student stu1;   // 구조체 변수 선언
    struct student stu2 = { 1234, "aaa", 88 };
    struct student stu3;

    stu3.id = 4567;
    strcpy(stu3.name, "ccc");
    stu3.score = 90;

    printf("[ stu3 ]\n");
    printf("id : %d\n", stu3.id);
    printf("name : %s\n", stu3.name);
    printf("score : %d\n", stu3.score);

    stu1 = stu2;   // 구조체 변수 stu1에 stu2값을 저장한다.(객체 복사)
                   // 구조체 멤버 변수의 자료형이 같아도 구조체가 다르면 복사되지 않는다.

    if (stu1.id == stu2.id && strcmp(stu1.name, stu2.name) == 0 && stu1.score == stu2.score)
        printf("\nstu1 and stu1 are equal.\n");

    return 0;
}

 


#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

struct student_1 {   // student 구조체 선언
    int id;
    char name[20];
    int score;
};

struct student_2 {
    int id;
    char name[20];
    int score;
};

int main(){

    struct student_1 stu1 = { 1234, "aaa", 88 };
    struct student_2 stu2;

    stu1 = stu2;   // 에러: struct student_1 형식의 값을 struct student_2 형식의 엔터티에 할당할 수 없습니다.

    return 0;
}
반응형