指向指针数组的指针数组-4个*指针

前言

C语言中,一般在项目中,指针非常常见,即*p, 表示指向一个变量的地址;也很常见两个指针的变量,即**p , 这表明此指针指向一个元素为指针的数组。
但是在nginx中,有一个指针定义为:

void                  ****conf_ctx

这实际上表示此指针指向一个元素为指针数组的指针数组。
所以写一个小程序来实现一个指向指针数组的指针数组的指针。

内存布局

这里写图片描述

代码

/*默认认为malloc肯定能成功,没有做返回值NULL的处理,偷懒了*/
#include <stdio.h>
#include <stdlib.h>

#define MODLE_N 5
#define CONF_N  4
/*not check malloc success or not*/
int main () {
    char **location;
    char ****module;

    module = (char ****)malloc(MODLE_N * sizeof(char *));
    int j = 0; 

    for  (;j < MODLE_N; j++) {

        location = (char **)malloc(CONF_N * sizeof(char *) );
        module[j] = (char ***)location;
        int i = 0;
        for (;i<CONF_N; i++) {
            location[i] = malloc(20 * sizeof(char));
            sprintf(location[i], "test-message-%d", i);
        } 
    }
    for (j = 0 ; j < MODLE_N; j++ ){

        int i; 
        for (i=0;i<CONF_N;i++){
            printf("module %d, config %d, content: %s\n", j, i,module[j][i]);
        }

        char **location  = (char **)module[j]; 
        for (i=0;i<CONF_N;i++){
            free(location[i]);
        }
        free(location);
    }

    free (module);
}

运行结果

使用valgrind运行,顺便确认没有内存泄漏

[liuguirong@cdn07v ~/lgr/c]$ valgrind --tool=memcheck --leak-check=yes ./a.out 
==2969== Memcheck, a memory error detector
==2969== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2969== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2969== Command: ./a.out
==2969== 
module 0, config 0, content: test-message-0
module 0, config 1, content: test-message-1
module 0, config 2, content: test-message-2
module 0, config 3, content: test-message-3
module 1, config 0, content: test-message-0
module 1, config 1, content: test-message-1
module 1, config 2, content: test-message-2
module 1, config 3, content: test-message-3
module 2, config 0, content: test-message-0
module 2, config 1, content: test-message-1
module 2, config 2, content: test-message-2
module 2, config 3, content: test-message-3
module 3, config 0, content: test-message-0
module 3, config 1, content: test-message-1
module 3, config 2, content: test-message-2
module 3, config 3, content: test-message-3
module 4, config 0, content: test-message-0
module 4, config 1, content: test-message-1
module 4, config 2, content: test-message-2
module 4, config 3, content: test-message-3
==2969== 
==2969== HEAP SUMMARY:
==2969==     in use at exit: 0 bytes in 0 blocks
==2969==   total heap usage: 26 allocs, 26 frees, 600 bytes allocated
==2969== 
==2969== All heap blocks were freed -- no leaks are possible
==2969== 
==2969== For counts of detected and suppressed errors, rerun with: -v
==2969== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值