- 论坛徽章:
- 1
|
今天看今天看《linux C一站式编程》关于两层指针有点疑问;
书上是这样讲的:
- /* 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;
- }
复制代码 思考一下,为什么在main函数中不能直接调用free(p)释放内存,而要调用free_unit(p)?为什么一层指针的函数接口void alloc_unit(unit_t *p);不能分配内存,而一定要用两层指针的函数接口?
但是我在vc++ 6.0中可以在main函数中直接调用free(p)释放内存啊;为什么书上说不能直接调用free(p)呢?还是在main函数中调用free(p)根本不会释放内存?还请大牛们指点;
还有关于两层指针还有那些功能呢?
|
|