구조를 통해 사용자 정의 데이터 유형을 생성할 수 있습니다. 구조 멤버는 기본 데이터 유형이거나 정적으로 할당된 메모리의 배열일 수 있습니다. 한 구조 변수를 다른 구조 변수에 할당하면 얕은 복사가 수행됩니다. 그러나 구조 멤버가 배열인 경우 컴파일러가 자동으로 전체 복사를 수행하는 예외가 있습니다. 예를 들어 이것을 봅시다 -
예시
#include <stdio.h>
#include <string.h>
typedef struct student {
int roll_num;
char name[128];
}
student_t;
void print_struct(student_t *s) {
printf("Roll num: %d, name: %s\n", s->roll_num, s->name);
}
int main() {
student_t s1, s2;
s1.roll_num = 1;
strcpy(s1.name, "tom");
s2 = s1;
// Contents of s1 are not affected as deep copy is performed on an array
s2.name[0] = 'T';
s2.name[1] = 'O';
s2.name[2] = 'M';
print_struct(&s1);
print_struct(&s2);
return 0;
} 출력
위의 코드를 컴파일하고 실행하면 다음과 같은 출력이 생성됩니다 -
Roll num: 1, name: tom Roll num: 1, name: TOM