简体   繁体   中英

Pointer to a Function in a Struct

I have the following struct:

struct A {
   struct list * (* get_items) (void);
   char * (*build) (void);
}

Now the way build is assigned (which is a pointer to a function) is as follows:

struct A someVar = {
  .build = someBuildingFunction
};

I am not sure about the syntax for how build is assigned. Why is it starting with a dot? And furthermore, how would I point get_items to the appropriate function in struct A someVar ? I've tried several ways and I keep getting errors.

I also noticed the lack of semicolon at the end of somebuildingFunction . Why is that?

Why is it starting with a dot?

It's called a designated initializer.

how would I point get_items to the appropriate function in struct A someVar?

struct A someVar = {
  .build = someBuildingFunction,
  .get_items = someGettingFunction
};

You could omit the names of the members and just make sure you put the function names in the right order.

I also noticed the lack of semicolon at the end of somebuildingFunction. Why is that?

That's common for initializers in C. For example:

int x[] = {
    1 /* No semicolon after 1. */
}; 

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