在C中调用结构体成员
我有一个关于 C 的问题,非常感谢那些愿意分享他们知识的人。
当我阅读代码时,我偶然发现了一个结构,该结构的成员以我以前从未见过的方式被调用。 代码基本上如下:
的结构成员的代码
struct struct_name gzw;
gzw.cb = otherfunct;
调用下面定义结构
struct struct_name {
int bela;
unsigned int packet;
int (*cb)(struct struct_name *fd, unsigned int packet2);
};
我有点困惑,因为据我所知,cb 成员应该是一个指针,有两个参数,不是吗?为什么 struct_name 可以调用 "cb" ,而不是 (*cb with 2 个参数) ?
感谢您的善意回复
I have a question regarding C, would appreciate those who are willing to share their knowledge.
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? howcome struct_name can call "cb" , and not (*cb with 2 parameters) ?
Thank you for your kindness response
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的你是对的。成员变量cb是一个函数指针变量,接受一个struct struct_name*和一个整数作为输入并返回一个int。
要调用该函数,您必须执行以下操作:
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.To call the function you have to do something like this:
cb
是一个函数指针。您可以将其指定为指向原型(即参数编号、类型和返回类型)与函数指针类型匹配的任何函数。然后您可以通过函数指针调用该函数,如下所示:
cb
is a function pointer. You can assign it to point at any function whose prototype (i.e. argument number, types and return type) matches that of the function-pointer type.You can then call that function via the function pointer, as:
CB 成员是一个函数指针,它带有两个参数并返回 int。您感到困惑的调用是分配指针值,因此不需要引用参数。调用该函数时,将使用参数
gzw.cb(p1,p2)
。the CB member is a function pointer that takes two parameters and returns and 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)
.这是一个函数指针。基本上,您可以像分配任何其他值一样向结构分配一个函数。
This is a function pointer. Basically, you assign a function to the struct like you would assign any other value.
是的,cb 是一个函数指针,它接受两个参数并返回一个 int。
说“struct_name calls
cb
”是不正确的,该结构包含一个函数指针,您可以使用gzw.cb(arg1, arg2); 调用该函数指针。
。Yes,
cb
is a function pointer that takes two arguments and returns an int.It is not correct to say "struct_name calls
cb
" Instead, the structure contains a function pointer which you can call withgzw.cb(arg1, arg2);
.