如何使用结构在 C 中使用函数指针?

How to use function pointers in C using structs?

我正在尝试使用函数指针和结构打印时间。它没有给出任何错误。它首先起作用,但后来 "Test.exe stopped running!"。

我的文件是:Random.c Random.h , Randomness.c Randomness.h, Test.c

Random.h

struct RANDOM {
    char* date;
    char* (*Date) (struct RANDOM*);
    void (*Write) (struct RANDOM*);
};
typedef struct RANDOM* Random;

Random CreateRandom();
char* DateOfNow(const Random);
void WriteDate(const Random);

Random.c

char* BringTime(){
    char* buff = malloc(sizeof(char)*100);
    time_t now = time(0);
    strftime(buff, 100, "%Y-%m-%d %H:%M",localtime(&now));

    return buff;
}

Random CreateRandom(){
    Random this;
    this = (Random) malloc(sizeof(struct RANDOM));  
    this->date = BringTime();

    return this;
}

char* DateOfNow(const Random this){
     return this->date;
}

void WriteDate(const Random this){
    printf("\n\n Date is: %s", this->date);
}

Randomness.h

struct RANDOMNESS{
    Random super;
};

typedef struct RANDOMNESS* Randomness;

Randomness CreateRandomness();

Randomness.c

Randomness CreateRandomness(){
    Randomness this;
    this = (Randomness)malloc(sizeof(struct RANDOMNESS));
    this->super = CreateRandom();

    return this;
}

Test.c

int main() {

    Randomness rnd = CreateRandomness();
    printf("works till here");
    rnd->super->Write(rnd->super);
}

输出是:工作到这里

输出后停止 运行 "Test.exe stopped running".

我试过了 printf("%p", rnd->super) 它给了我地址。所以也许 Write(rnd->super) 函数有问题。

您必须将函数指针分配给结构中的成员字段:

Random CreateRandom(){
    Random this;
    this = (Random) malloc(sizeof(struct RANDOM));  
    this->date = BringTime();
    // assign function pointer to actual functions
    this->Date = &DateOfNow; 
    this->Write = &WriteDate;

    return this;
}

当然,DateOfNowWriteDate 的原型应该在 CreateRandom 定义之前可用。

注意:你可以写this->Date = DateOfNow;(没有&因为&有函数标识符是多余的)。

您的创建函数不完整:

Random CreateRandom(){
    Random this;
    this = (Random) malloc(sizeof(struct RANDOM));  
    // Content of the memory is undefined!
    this->date = BringTime();
    // What about Write() and Date()? <<<======= ERROR IS HERE
    return this;
}

...

Randomness CreateRandomness(){
    Randomness this;
    this = (Randomness)malloc(sizeof(struct RANDOMNESS));
    this->super = CreateRandom();

    return this;
}

...

int main() {

    Randomness rnd = CreateRandomness();
    printf("works till here");
    rnd->super->Write(rnd->super); // << using unspecified values is undefined behaviour.
}

您将一些值分配给 date 但没有分配给 DateWrite。 这意味着您在 rnd->super 中有一些有用的值,但 rnd->super->Write 的内容未定义。

如果要将 Create* 函数用作一种构造函数,还必须正确设置函数指针。