nginx数组使用技巧

多个字符串构成的数组

#define STR_NUM 3
#define STR_MAX_LEN 64
int main()
{
    char strs[STR_NUM][STR_MAX_LEN] = { "ok", "xxx", "yyy" };
    return 0;
}

如上面代码所示,存在两个比较恶心地方:

  1. 每个字符串的最大长度要设置,实际上大部分我们不需要知道最大长度;
  2. 必须要设置最大字符串个数。

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;
}

如代码所示,技巧如下:

  1. 数组最后一个一定是NULL,因为通过NULL判定是否是最后一个;
  2. 遍历的时候,只需要将值放到for循环条件即可,如代码中的g_apcInfos[i];
  3. 字符串的个数为循环后的i值;
  4. 当然,也可以通过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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值