struct Std {
char name[4];
};
struct Std student;
student.name = {'a', 'c', 'f', 'g'}; // ❌ 編譯錯誤
C 語言規定:**數組類型成員只能在聲明(定義)時進行整體初始化**,後續賦值只能逐元素賦值,或使用庫函數(如 strcpy、memcpy)。
struct Std student = {"acfg"}; // 字符串字面量自動補 \0
// 或
struct Std student = {{'a','c','f','g'}}; // 顯式列表,注意雙層大括號
student.name[0] = 'a';
student.name[1] = 'c';
student.name[2] = 'f';
student.name[3] = 'g'; // 若作字符串用,需手動加 \0
#include <string.h>
strcpy(student.name, "acf"); // 自動補 \0,確保目標空間足夠
struct Std class[3] = {
{"Tom"},
{"Jerry"},
{"Bob"}
};
char name[4] 只能存 3 個可見字符 + \0,若存 4 字符將無結束符,導致 printf("%s") 越界讀取。s1 = s2 是**整體逐字節拷貝**,包含數組成員,這在聲明後賦值是合法的:struct Std s1 = {"abc"};
struct Std s2;
s2 = s1; // ✅ 合法,數組內容一同拷貝
記住:**聲明時一次性初始化最簡潔安全;事後修改請用逐元素或庫函數。**