简体   繁体   中英

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 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 (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.

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); .

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) .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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