简体   繁体   English

在C中调用Struct成员

[英]call Struct member in C

I have a question regarding C, would appreciate those who are willing to share their knowledge. 我对C有一个疑问,非常感谢那些愿意分享知识的人。

While I was reading a code, I got stumbbled in a struct that its member is called in a way that I have never seen before. 当我阅读代码时,我迷上了一个结构,以一种从未见过的方式调用它的成员。 The code basically is below : 代码基本上如下:
Code to call the struct member 调用结构成员的代码

struct struct_name gzw;
gzw.cb = otherfunct;

where the struct is defined below 结构在下面定义

struct struct_name {
        int bela;
        unsigned int packet;
        int (*cb)(struct struct_name *fd, unsigned int packet2);
};

I kinda confused, because as I know, the cb member should be a pointer, with two parameter isn't it? 我有点困惑,因为据我所知,cb成员应该是一个带有两个参数的指针,不是吗? howcome struct_name can call "cb" , and not (*cb with 2 parameters) ? 如何struct_name可以调用“ cb”,而不能(带有2个参数的* cb)?

Thank you for your kindness response 谢谢您的好意回复

cb is a function pointer . cb是一个函数指针 You can assign it to point at any function whose prototype (ie argument number, types and return type) matches that of the function-pointer type. 您可以将其分配给指向原型(即参数编号,类型和返回类型)与功能指针类型相匹配的任何函数的指针。

You can then call that function via the function pointer, as: 然后,您可以通过函数指针调用该函数,如下所示:

gzw.cb(arg1, arg2);

This is a function pointer. 这是一个函数指针。 Basically, you assign a function to the struct like you would assign any other value. 基本上,您可以像分配其他任何值一样向该结构分配一个函数。

Yes, cb is a function pointer that takes two arguments and returns an int. 是的, cb是一个函数指针,它带有两个参数并返回一个int。

It is not correct to say "struct_name calls cb " Instead, the structure contains a function pointer which you can call with gzw.cb(arg1, arg2); 说“ struct_name 调用 cb ”是不正确的,相反,该结构包含一个函数指针,可以使用gzw.cb(arg1, arg2);进行调用gzw.cb(arg1, arg2); .

the CB member is a function pointer that takes two parameters and returns and int. CB成员是一个函数指针,它接受两个参数并返回和int。 The call you are confused about is assigning a pointer value and therefore does not need to reference the parameters. 您感到困惑的调用是分配指针值,因此不需要引用参数。 to the call the function the parameters would be used gzw.cb(p1,p2) . 调用该函数时,将使用参数gzw.cb(p1,p2)

yes you are right. 是的,你是对的。 the member variable cb is a function pointer variable, taking a struct struct_name* and an integer as input and returns an int. 成员变量cb是一个函数指针变量,采用struct struct_name*和一个整数作为输入并返回一个int。

To call the function you have to do something like this: 要调用该函数,您必须执行以下操作:

int ret = gzw.cb(&gzw, 10);

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

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