头文件 point.h
#ifndef DP
#define DP
char *get_day(int);
void get_a_day(const char**);
#endif
函数文件 point.c
#include "doublepoint.h"
#include <string.h>
static const char *msg[] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
};
void get_a_day(const char **p)
{
//static 定义变量相当于预定义,下次再次调用该函数时变量为改变值
//既第二次调用get_a_day时, i = 1;
static int i = 0;
*p = msg[i % 7];
i++;
}
/*
*返回值为指针,则返回的地址没变,地址内存中的值可以改变
*/
char *get_day(int idx)
{
static char buf[20];
strcpy(buf, msg[idx]);
return buf;
}
main.c
#include "doublepoint.h"
#include <stdio.h>
int main(void)
{
const char *firstda = NULL;
const char *secondda = NULL;
char *firstday = get_day(0);
char *secondday;
secondday = get_day(1);
//firstday的值为Monday,因为firstday与secondday指向的内存地址一样的,
//而在secondday = get_day(1)中secondday对应的内存值改变为"Monday"
printf("%s\n", firstday);
get_a_day(&firstda);
get_a_day(&secondda);
//最后输出的值为"Sunday Monday"
//用gdb调试时,i保留位上次改变值,而非i = 0;
printf("%s\t %s\n",firstday, secondday);
return 0;
}
综上所述,双指针参数可以作为传出参数,即void function(char **pp)中可以给*pp分配空间,定义等,与返回值为单指针char *pchar(void)一样,可以分配空间