指向指针数组的指针数组-4个*指针
程序员文章站
2024-01-03 08:58:10
...
前言
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运行,顺便确认没有内存泄漏
[aaa@qq.com ~/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)