โครงสร้างช่วยให้เราสร้างประเภทข้อมูลที่กำหนดโดยผู้ใช้ สมาชิกโครงสร้างสามารถเป็นประเภทข้อมูลดั้งเดิมหรืออาจเป็นอาร์เรย์ของหน่วยความจำที่จัดสรรแบบสถิต เมื่อเรากำหนดตัวแปรโครงสร้างหนึ่งให้กับตัวแปรอื่น จะมีการคัดลอกแบบตื้น อย่างไรก็ตาม มีข้อยกเว้น ถ้าสมาชิกโครงสร้างเป็นอาร์เรย์ คอมไพเลอร์จะทำสำเนาลึกโดยอัตโนมัติ เรามาดูตัวอย่างกัน −
ตัวอย่าง
#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