简体   繁体   English

指向结构中函数的指针

[英]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: 现在,分配build的方式(这是指向函数的指针)如下:

struct A someVar = {
  .build = someBuildingFunction
};

I am not sure about the syntax for how build is assigned. 我不知道有关语法如何build分配。 Why is it starting with a dot? 为什么以点开头? And furthermore, how would I point get_items to the appropriate function in struct A someVar ? 而且,如何将get_items指向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 . 我还注意到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? 我如何将get_items指向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. 我还注意到somebuildingFunction的结尾缺少分号。 Why is that? 这是为什么?

That's common for initializers in C. For example: 这对于C语言中的初始化程序很常见。例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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