用戶定義結構體:
struct Student {
char name; // 錯誤:單字符
char age;
char sex;
};
輸入時 scanf("%s", &st.name) 導致緩衝區溢出、程序卡死或崩潰。
| 定義 | 類型 | scanf 格式 | 說明 |
|---|---|---|---|
char name[10] | 字符數組 (字符串) | %s (讀至空白) | 需分配足夠空間含結束符 \0 |
char name | 單字符 | %c (讀單字符含空格) | 無法存儲名字 |
char *name | 指針 | 需先 malloc | 動態分配 |
struct Student {
char name[20]; // 字符數組,最長 19 字符 + \0
int age; // 年齡用 int,%d
char sex; // 性別單字符 'M'/'F',%c
};
struct Student st;
printf("輸入姓名 年齡 性別: ");
// %19s 防止溢出,%c 前加空格跳過換行/空格
if (scanf("%19s %d %c", st.name, &st.age, &st.sex) != 3) {
printf("輸入格式錯誤\n");
return 1;
}
printf("錄入: %s, %d, %c\n", st.name, st.age, st.sex);
%19s 防溢出。" %c"。char name[20]; int age; 中間可能有 3 字節填充,sizeof(Student) 可能為 28 而非 24,不影響邏輯但影響二進制寫入。fgets 或 scanf("%19s")。