函数指针返回值的问题

时间:2014-06-12 23:08:23

标签: c function-pointers void-pointers

我有以下SSCCE:

#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <string.h>

#define streq(x, y) (strcmp((x), (y)) == 0)
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

typedef struct
{
    const char *cmd;
    void* (*fn)(void);
} __attribute__((__packed__)) Command;

void* getTime(void)
{
    return ((void*)((uintptr_t)time(NULL)));
}

void* getDay(void)
{
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    return ((void*)((uintptr_t)(tm.tm_wday)));
}

static Command commands[] =
{
    {"time", getTime},
    {"day", getDay},
};

int main(int argc, char *argv[])
{
    for (int i = 0; i < ARRAY_SIZE(commands); ++i)
    {
        Command *p = commands+i;
        if (streq(argv[1], p->cmd)) printf("%d\n", (int)p->fn);
    }
}

我的问题是为什么我这样运行代码:

./test day

返回值为3648,而不是指定为here的0-6之间的值。

1 个答案:

答案 0 :(得分:3)

您需要调用该功能。现在你只是打印函数指针值。以下代码应该这样做:

if (streq(argv[1], p->cmd)) printf("%d\n", (int)(p->fn()));