跳转到内容

3. 两层指针的参数

c
/* redirect_ptr.h */
#ifndef REDIRECT_PTR_H
#define REDIRECT_PTR_H

extern void get_a_day(const char **);

#endif

想一想,这里的参数指针是const char **,有const限定符,却不是传入参数而是传出参数,为什么?如果是传入参数应该怎么表示?

c
/* redirect_ptr.c */
#include "redirect_ptr.h"

static const char *msg[] = {"Sunday",   "Monday", "Tuesday", "Wednesday",
                            "Thursday", "Friday", "Saturday"};
void get_a_day(const char **pp) {
    static int i = 0;
    *pp = msg[i % 7];
    i++;
}
c
/* main.c */
#include <stdio.h>

#include "redirect_ptr.h"

int main(void) {
    const char *firstday = NULL;
    const char *secondday = NULL;
    get_a_day(&firstday);
    get_a_day(&secondday);
    printf("%s\t%s\n", firstday, secondday);
    return 0;
}