简体   繁体   中英

What is the right way of creating and initializing a struct containing a function pointer in C?

I have done my reading in structs but everywhere I see different ways of creating them and initializing them. Can you please tell me your opinion on the way I've done it and point out what would you change and why!

in the header:

typedef void (*ActionFunc)(void);

typedef struct {
    ActionFunc func;
} MyStruct;

in the C file:

static MyStruct* my_struct;

void action(){
    /*....*/
}

void my_function(){
    my_struct = &(MyStruct){
        .func = action
    };
}

I don't understand why you've made my_struct into a pointer.

The initialization in my_function() won't work, you're setting my_struct to the address of a compound literal, which won't stick around when my_function exits.

Just make my_func a proper global structure (if that's what you need), not a pointer, and change it directly.

static MyStruct my_struct;

void my_function(void)
{
  my_struct.func = action;
}

You can access the stored function pointer from anywhere ( my_struct is global , after all!) like so:

void random_function(void)
{
  extern struct MyStruct my_struct;

  my_struct.func();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM