1

I have the following 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);
    }
}

My question is why when I run the code as such:

./test day

The return value is 3648 and not a value from 0-6 as specified here.

1 Answer 1

3

You need to call the function. Right now you're just printing the function pointer value. The following code should do it:

if (streq(argv[1], p->cmd)) printf("%d\n", (int)(p->fn()));
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it had to be something simple that I was overlooking. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.