c - 如何使用结构在 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)
功能有问题。
解决方案
您必须将函数指针分配给结构中的成员字段:
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
应该WriteDate
在CreateRandom
定义之前可用。
注意:你可以写this->Date = DateOfNow;
(不&
带&
函数标识符是多余的)。
推荐阅读
- java - Firebase Crashlytics ObjectOutputStream writeObject0 错误
- reactjs - TypeScript: how to find an object in an array and return that specific object?
- stm32 - HAL/Bare Metal/RTOS/Other OS 中最好的开发平台
- javascript - 如何在 react.js 中呈现嵌套的 JSON?
- python - 从 csv 中提取和操作数据 - 查找唯一值并显示另一列中的相应数据
- marklogic - MarkLogic ml-gradle 版本
- action - 如何在谷歌操作中处理槽值中的空格
- django - 覆盖 django 管理面板中的 admin_menu.py 文件以进行侧边栏自定义
- ansible - 在主机上执行任务的正确方法
- .net - 在工件上上传时,Angular 应用程序的包版本控制不会自动更新