darksky
darksky

Reputation: 21019

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?

Upvotes: 2

Views: 126

Answers (1)

cnicutar
cnicutar

Reputation: 182609

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. */
}; 

Upvotes: 5

Related Questions