Created
March 31, 2016 06:24
-
-
Save limboinf/800b1f62026f701108241062cf7e93cd to your computer and use it in GitHub Desktop.
C两层指针的参数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "redirect_ptr.h" | |
/* | |
总结一下,两层指针参数如果是传出的,可以有两种情况: | |
第一种情况,传出的指针指向静态内存(比如上面的例子),或者指向已分配的动态内存(比如指向某个链表的节点); | |
第二种情况是在函数中动态分配内存,然后传出的指针指向这块内存空间. | |
这种情况下调用者应该在使用内存之后调用释放内存的函数,调用者的责任是请求分配和请求释放内存, | |
实现者的责任是完成分配内存和释放内存的操作。 | |
由于这两种情况的函数接口相同,应该在文档中说明是哪一种情况。 | |
*/ | |
int main(int argc, const char * argv[]) { | |
const char *firsday = NULL; | |
const char *secondday = NULL; | |
get_a_day(&firsday); | |
get_a_day(&secondday); | |
printf("%s\t%s\n", firsday, secondday); | |
printf("------------------------\n"); | |
unit_t *p = NULL; | |
alloc_unit(&p); | |
printf("number: %d\nmsg: %s\n", p->number, p->msg); | |
free_unit(p); | |
p = NULL; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include "redirect_ptr.h" | |
static const char *msg[] = {"Sunday", | |
"Monday", "Tuesday", "Wednesday", | |
"Thursday", "Friday", "Saturday"}; | |
/* | |
两层指针也是指针,同样可以表示传入参数、传出参数或者Value-result(传入和传出)参数 | |
只不过该参数所指的内存空间应该解释成一个指针变量 | |
*/ | |
void get_a_day(const char **pp) | |
{ | |
static int i=0; | |
*pp = msg[i%7]; | |
i++; | |
} | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef redirect_ptr_h | |
#define redirect_ptr_h | |
#include <stdio.h> | |
typedef struct { | |
int number; | |
char *msg; | |
} unit_t; | |
extern void get_a_day(const char **); | |
extern void alloc_unit( unit_t **); | |
extern void free_unit(unit_t *); | |
#endif /* redirect_ptr_h */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment