开发者

call Struct member in C

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开发者_Python百科 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


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:

gzw.cb(arg1, arg2);


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.


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 with gzw.cb(arg1, arg2);.


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:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜