首页 > 解决方案 > 如何使用结构在 C 中使用函数指针?

问题描述

我正在尝试使用函数指针和结构来打印时间。它没有给出任何错误。它首先工作,但后来“Test.exe 停止运行!”。

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

随机.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);

随机的.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);
}

随机性.h

struct RANDOMNESS{
    Random super;
};

typedef struct RANDOMNESS* Randomness;

Randomness CreateRandomness();

随机性.c

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

    return this;
}

测试.c

int main() {

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

输出是:工作到这里

在该输出之后,它停止运行“Test.exe 停止运行”。

我试过printf("%p", rnd->super)它给了我地址。所以可能是Write(rnd->super)功能有问题。

标签: cstructmingwfunction-pointers

解决方案


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

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;
}

当然,原型DateOfNow应该WriteDateCreateRandom定义之前可用。

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


推荐阅读