在 C 中使用带有 void 的函数指针

Use function pointer with void in C

我想在 C 中创建一个类似于课程注册的结构。为此,我使用了 struct 而不是 table。

STUDENT *createStudent(){
    return (STUDENT *) malloc(sizeof(STUDENT));
}

TEACHER *createTeacher(){
    return (TEACHER *) malloc(sizeof(TEACHER));
}

COURSE *createCourse(){
    return (COURSE *) malloc(sizeof(COURSE));
}

COURSEREGISTRATION *createCourseRegistration(){
    return (COURSEREGISTRATION *) malloc(sizeof(COURSEREGISTRATION));
}

我想将这些函数传递给一个带有函数指针的变量。喜欢;

void *createNode(int choise){
    void (*fp[]) () = {createStudent, createTeacher, createCourse, createCourseRegistration};
    return (fp[choise] ());
}

我想用 func 指针 malloc 并在这个函数(主函数)中得到一个错误;

STUDENT *studentHead = NULL;
void *temp = studentHead;
temp = createNode(0);//Zero for student

我对函数指针的理解不是很清楚。我应该怎么办?我哪里做错了?或者我可以在这种情况下使用 func 指针吗?

谢谢

编辑: 我是这样解决问题的;

#define CREATESTUDENT 0
#define CREATETEACHER 1
#define CREATEDCOURSE 2
#define CREATECOURSEREGISTRATION 3

void createNode(void **temp, int choise){
    switch(choise){
        case CREATESTUDENT:
            *temp = (STUDENT *) malloc(sizeof(STUDENT));
            break;
        case CREATETEACHER :
            *temp = (TEACHER *) malloc(sizeof(TEACHER));
            break;
        case CREATEDCOURSE :
            *temp = (COURSE *) malloc(sizeof(COURSE));
            break;
        case CREATECOURSEREGISTRATION :
            *temp = (COURSEREGISTRATION *) malloc(sizeof(COURSEREGISTRATION ));
            break;
    }
}

并使用调用函数;

STUDENT *temp = studentHead;
createNode(&temp, CREATESTUDENT);

根据您的代码,fp 是一个 void,而不是 void* 函数。无论 choice.

你总是从 createNode 返回任何东西

您将 fp 声明为 {

void (*fp[]) () = {

这是指向函数的指针数组 returning void。你想要 return 指针的函数,所以你想要

void *(*fp[])() = {

但是你仍然有问题,你用来初始化这个数组的函数指针是错误的类型——它们都是 return 指向真实类型(不是 void)的函数。因此,虽然这 可能 有效,但就标准而言,它实际上是未定义的行为。

如果您将所有 create 函数更改为 return void * 而不是 STUDENT *(和类似的),那么它将是安全的。

简短回答:您的函数 ptr 签名是 void () 而不是 void* ()

happily celebrating c++ does not care that much about function return types :)

TL;DR;

为什么要让生活变得比他们需要的更艰难? 为什么不使用简单的开关

void *createNode(int choice){
  switch(choice){
    case 0:
      return createStudent();
    case 1:
      return createTeacher();
    ...
    ...
  }
}

Note: I don't see the point of creating createNode from the first place. it seems misleading signature, and i'd make the API user call createStudent, createTeacher, etc explicitly.

一些编码风格建议:

  • typedef 你的函数签名
  • 声明你的函数数组(最好作为模块的成员或静态)