简体   繁体   中英

Pass struct member to function pointer in same struct in C

I need to pass a struct member such as "str" in the following example as an argument to a function pointer in same struct such as "(ToUpper)", or by another words I need to access the value of "str" inside the "ToUpper" function.

typedef struct _String {
            char* str;
            char* (*ToUpper) (void);
         } String;

Can I do it in this way ?

Since there's no this pointer in C, you have to pass a reference to whatever object you're manipulating when working with function pointers in structs...

typedef struct _String {
    char* str;
    char* (*ToUpper)( struct _String );
} String;

Then you should have an "initialize" function that is like this..

char* ToUpper( struct _String s ) {
   // ...
}

String newString(char* str) {
    return (String) { str, ToUpper };
}

That second method there will give you a new String struct with all the function pointers set so you can use it.

Call it like this:

someString.ToUpper(someString)

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