多个字符串构成的数组
#define STR_NUM 3
#define STR_MAX_LEN 64
int main()
{
char strs[STR_NUM][STR_MAX_LEN] = { "ok", "xxx", "yyy" };
return 0;
}
如上面代码所示,存在两个比较恶心地方:
- 每个字符串的最大长度要设置,实际上大部分我们不需要知道最大长度;
- 必须要设置最大字符串个数。
demo
#include <stdio.h>
char* g_apcInfos[] =
{
"ok",
"xxx",
"yyy",
NULL
};
int main()
{
unsigned int i = 0;
for (i = 0; g_apcInfos[i]; ++i)
{
printf("%s\n", g_apcInfos[i]);
}
int strs_num = i;
int strs_num2 = sizeof(g_apcInfos) / sizeof(char*) - 1;
system("pause");
return 0;
}
如代码所示,技巧如下:
- 数组最后一个一定是NULL,因为通过NULL判定是否是最后一个;
- 遍历的时候,只需要将值放到for循环条件即可,如代码中的g_apcInfos[i];
- 字符串的个数为循环后的i值;
- 当然,也可以通过str_num2的方式计算字符串个数。
最后,列出nginx的类似用法(精简):
#include <ngx_config.h>
#include <ngx_core.h>
extern ngx_module_t ngx_core_module;
extern ngx_module_t ngx_errlog_module;
extern ngx_module_t ngx_conf_module;
extern ngx_module_t ngx_openssl_module;
extern ngx_module_t ngx_regex_module;
ngx_module_t *ngx_modules[] = {
&ngx_core_module,
&ngx_errlog_module,
&ngx_conf_module,
&ngx_openssl_module,
&ngx_regex_module,
NULL // 一定要注意此处有个NULL
};
char *ngx_module_names[] = {
"ngx_core_module",
"ngx_errlog_module",
"ngx_conf_module",
"ngx_openssl_module",
"ngx_regex_module",
NULL // 一定要注意此处有个NULL
};
ngx_int_t ngx_preinit_modules(void)
{
ngx_uint_t i;
for (i = 0; /* 此处通过NULL结束循环 */ngx_modules[i]; i++)
{
ngx_modules[i]->index = i;
ngx_modules[i]->name = ngx_module_names[i];
}
/* 统计元素个数 */
ngx_modules_n = i;
return NGX_OK;
}