我正在尝试使用函数指针和结构打印时间。它不会产生任何错误。它首先工作,但后来"Test.exe停止运行!“。
我的文件是: 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);
}输出为: works is here
在该输出之后,它将停止运行"Test.exe stops“。
我试过printf("%p", rnd->super),它给了我地址。因此,Write(rnd->super)函数可能存在问题。
发布于 2019-04-12 22:21:57
您必须将函数指针分配给结构中的成员字段:
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; (没有&,因为带有函数标识符的&是一个剩余)。
发布于 2019-04-12 22:23:36
您的create函数不完整:
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赋值,但不为Date和Write赋值。这意味着您在rnd->super中有一些有用的值,但是rnd->super->Write的内容是未定义的。
如果要将Create*函数用作一种构造函数,还必须正确设置函数指针。
https://stackoverflow.com/questions/55653029
复制相似问题