반응형
같은 구조체는 객체를 복사할 수 있다.
#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;
}
반응형
'C' 카테고리의 다른 글
[C언어] 실습: 이름을 검색하여 해당하는 연락처 출력하기 (구조체) (0) | 2021.05.22 |
---|---|
[C언어] 실습: 구조체 'student'로 3명의 총점 및 평균을 계산하는 성적 처리 프로그램 구현하기 (0) | 2021.05.21 |
[C언어] 실습: 구조체 'car'로 자동차, 속도, 연료 상태 출력하기 (0) | 2021.05.19 |
[C언어] 실습: 구조체 'book'으로 책이름, 저자, 가격 출력하기 (0) | 2021.05.17 |
[C언어] 실습: 구조체 'people'로 이름, 나이, 신장 출력하기 (0) | 2021.05.16 |