static char c[10] = {'c',' ','p','r','o','g','r','a','m'};
// c[9] 自動為 0
static char c[] = "C program"; // 長度自動為 10
// 等價於 static char c[] = {"C program"};
字符串方式佔用長度+1 字節(含 \0)。
printf("%s\n", c); // 正確
// printf("%s", c[]); // 錯誤
char st[15];
scanf("%s", st); // 數組名即地址,無需 &
printf("%s\n", st);
%s 遇空格停止
// 輸入 "this is a book"
// 輸出 "this" — 空格後內容丟失
char st1[6], st2[6], st3[6], st4[6];
scanf("%s%s%s%s", st1, st2, st3, st4);
printf("%s %s %s %s\n", st1, st2, st3, st4);
// 輸出 "this is a book"
數組名在表達式中退化為首元素地址(&st[0]),本身即地址,加 & 類型錯誤(char (*)[15] vs char *)。
按數組名找到首地址,逐字符輸出直到遇到 \0。
main() {
int i, j;
char a[][5] = {{'B','A','S','I','C'}, {'d','B','A','S','E'}};
for (i=0; i<=1; i++) {
for (j=0; j<=4; j++) printf("%c", a[i][j]);
printf("\n");
}
}
// 輸出:
// BASIC
// dBASE
fgets 或 scanf("%[^\n]")scanf("%14s", st)string.h)