以字符串字面值初始化字符數組(static char c[]="BASIC\ndBASE";)會自動在末尾附加 \0,佔用額外 1 字節。輸出時用 printf("%s\n", c),格式字串 %s 直接接收數組名(首地址)。
\n)。範例對比:
/* gets 讀取整行 */
char st[15];
gets(st); puts(st); // 輸入 "this is a book" 完整輸出
/* scanf 遇空格截斷 */
scanf("%s", st); // 輸入 "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);
將一行字串按空格拆分存入多個數組,再合併輸出。
char c[10] 首地址假設為 2000,c 即代表 2000。scanf("%s", c) 正確,scanf("%s", &c) 錯誤。printf("%s", c) 從首址逐字輸出至 \0。