結構體中儲存字串時,可選擇固定大小陣列或指標配合動態記憶體。兩種方式在記憶體佈局、初始化便利性、彈性上有本質差異。
struct Student {
char name[LEN];
char address[LEN];
int age;
};
// 初始化簡單,字串儲存在結構體內部
struct Student s = {"bluemsun", "NENU", 25};
struct new_Student {
char *name;
char *address;
int age;
};
// 需手動分配與複製
struct new_Student s1;
char str[] = "zhouxy";
s1.name = (char*)malloc(strlen(str) + 1);
strcpy(s1.name, str);
陣列版本: 指標版本: +----------+ +----------+ | name[20] | | *name -----> [heap] "zhouxy" | addr[20] | | *addr -----> [heap] "EFGH" | age | | age | +----------+ +----------+ 40+ bytes 16 bytes (64-bit)
-> 運算子存取成員// 錯誤:直接指向字串常量,不可修改且生命週期不可控
struct new_Student s1 = {"zhouxy", "EFGH", 25};
// 正確:分配記憶體並複製
s1.name = malloc(strlen("zhouxy")+1);
strcpy(s1.name, "zhouxy");
理解結構體成員記憶體模型,能寫出更健壯、高效的 C 程式。