如果返回值传出的是指针,和(二级指针作为参数)通过参数传出指针类似,也分为两种情况:
第一种是传出指向静态内存或已分配的动态内存的指针(例1);
第二种是在函数中动态分配内存并传出指向这块内存的指针,这种情况通常还要实现一个释放内存的函数(例2)。
例1:返回指向已分配内存的指针:unit_t *func(void);
static const char *msg[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
char *get_a_day(int idx)
{
static char buf[20];
strcpy(buf, msg[idx]);
return buf;
}
例2:动态分配内存并返回指针:unit_t *alloc_unit(void);void free_unit(unit_t *p);
ret_allocator.h
#ifndef RET_ALLOCATOR_H
#define RET_ALLOCATOR_H
typedef struct {
int number;
char *msg;
} unit_t;
extern unit_t *alloc_unit(void);
extern void free_unit(unit_t *);
#endif
ret_allocator.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ret_allocator.h"
unit_t *alloc_unit(void)
{
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!");
return p;
}
void free_unit(unit_t *p)
{
free(p->msg);
free(p);
}
main.c
#include <stdio.h>
#include "ret_allocator.h"
int main(void)
{
unit_t *p = alloc_unit();
printf("number: %d\nmsg: %s\n", p->number, p->msg);
free_unit(p);
p = NULL;
return 0;
}
实参,形参,堆,栈,是否实参给形参传递赋值的过程中创建了新的变量。。。?这些问题思考清楚,答案就显而易见了。。。