Function pointer as a member of a C struct

后端 未结 5 1210
南笙
南笙 2020-12-02 07:08

I have a struct as follows, with a pointer to a function called \"length\" that will return the length of the chars member.

typedef struct pstring_t {
    ch         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 07:18

    You can use also "void*" (void pointer) to send an address to the function.

    typedef struct pstring_t {
        char * chars;
        int(*length)(void*);
    } PString;
    
    int length(void* self) {
        return strlen(((PString*)self)->chars);
    }
    
    PString initializeString() {
        PString str;
        str.length = &length;
        return str;
    }
    
    int main()
    {
        PString p = initializeString();
    
        p.chars = "Hello";
    
        printf("Length: %i\n", p.length(&p));
    
        return 0;
    }
    

    Output:

    Length: 5
    

提交回复
热议问题