温故而知新,实则菜狗重新看下
1. 引言
字符串数组通常有两类,一种为长度固定了(下图左);一种长度不固定(下图右)。如下图所示:
2. 使用
这里将显示月份的switch-case
替换成字符串数组。
#include <stdio.h>
int main(void)
{
const char *month_name[] = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December", };
int month;
printf("Please enter the number(1~12) of months: ");
scanf("%d", &month);
if (month >= 1 && month <= 12) {
printf("Current month: %s.\n", month_name[month - 1]);
} else {
printf("Input number Err.\n");
}
return 0;
}
另一个典型的使用即main
的接口中的argc
和argv[]
。简单测试如下:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int i;
for (i = 0; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
return 0;
}
测试结果:
$ ./test.exe hello china i love you
0: C:\workspace_vsc\C\test\str_arr_test.exe
1: hello
2: china
3: i
4: love
5: you