二级指针参数如果是传出的,可以有两种情况:
第一种情况,传出的指针指向静态内存(见例1),或者指向已分配的动态内存(比如指向某个链表的节点);
第二种情况是在函数中动态分配内存,然后传出的指针指向这块内存空间,这种情况下调用者应该在使用内存之后调用释放内存的函数,调用者的责任是请求分配和请求释放内存,实现者的责任是完成分配内存和释放内存的操作。
二级指针可以表示传入参数,传出参数或者Value-result参数。
例1. 用二级指针做传出参数的系统函数:
static const char *msg[] = {"Sunday", "Monday", "Tuesday", "Wedsday", "Thursday", "Friday", "Saturday"};
void get_a_day(const char **pp)
{
static int i = 0;
*pp = msg[i%7];
i++;
}
例2. 用二级指针分配内存,通过传出参数取得指向该内存的指针。一般来说,实现一个分配内存的函数就要实现一个释放内存的函数。
通过参数分配内存示例:void alloc_unit(unit_t **pp);
void free_unit(unit_t *p);
para_allocator.h
#ifndef PARA_ALLOCATOR_H
#define PARA_ALLOCATOR_H
typedef struct
{
int number;
char *msg;
} unit_t;
extern void alloc_unit(unit_t **);
extern void free_unit(unit_t *);
#endif
para_allocator.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "para_allocator.h"
void alloc_unit(unit_t **pp)
{
unit_t *p = malloc(sizeof(unit_t));
if(p == NULL) {
printf("out of memory\n");
exit(1);
}
p->number = 3;
p->msg = malloc(20);
strcpy(p->msg, "Hello World!");
*pp = p;
}
void free_unit(unit_t *p)
{
free(p->msg);
free(p);
}
main.c
#include <stdio.h>
#include "para_allocator.h"
int main(void)
{
unit_t *p = NULL;
alloc_unit(&p);
printf("number: %d\nmsg: %s\n", p->number, p->msg);
free_unit(p);
p = NULL;
return 0;
}
注:
两个新的预处理指示#ifndef PARA_ALLOCATOR_H和#endif,如果PARA_ALLOCATOR_H这个宏没有定义过,那么从#ifndef到#endif之间的代码就包含在预处理的输出结果中,否则这一段代码就不出现在预处理的输出结果中。para_allocator.h这个头文件的内容整个被#ifndef和#endif括起来了,如果在包含这个头文件时PARA_ALLOCATOR_H这个宏已经定义过了,则相当于这个头文件里什么都没有,包含了一个空文件。假如main.c包含了两次para_allocator.h:
则第一次包含para_allocator.h时并没有定义PARA_ALLOCATOR_H这个宏,因此头文件的内容包含在预处理的输出结果中;第二次再包含para_allocator.h就相当于包含了一个空文件,这就避免了头文件的内容被重复包含。这种保护头文件的写法称为Header Guard,每写一个头文件都要加上Header Guard,宏定义名就用头文件名的大写形式,这是规范的做法。