Function pointer as a member of a C struct

后端 未结 5 1193
南笙
南笙 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
    
    0 讨论(0)
  • 2020-12-02 07:22

    My guess is that part of your problem is the parameter lists not matching.

    int (* length)();
    

    and

    int length(PString * self)
    

    are not the same. It should be int (* length)(PString *);.

    ...woah, it's Jon!

    Edit: and, as mentioned below, your struct pointer is never set to point to anything. The way you're doing it would only work if you were declaring a plain struct, not a pointer.

    str = (PString *)malloc(sizeof(PString));
    
    0 讨论(0)
  • 2020-12-02 07:27

    The pointer str is never allocated. It should be malloc'd before use.

    0 讨论(0)
  • 2020-12-02 07:35

    Allocate memory to hold chars.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct PString {
            char *chars;
            int (*length)(PString *self);
    } PString;
    
    int length(PString *self) {
        return strlen(self->chars);
    }
    
    PString *initializeString(int n) {
        PString *str = malloc(sizeof(PString));
    
        str->chars = malloc(sizeof(char) * n);
        str->length = length;
    
        str->chars[0] = '\0'; //add a null terminator in case the string is used before any other initialization.
    
        return str;
    }
    
    int main() {
        PString *p = initializeString(30);
        strcpy(p->chars, "Hello");
        printf("\n%d", p->length(p));
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-02 07:37

    Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

    PString * initializeString() {
        PString *str;
        str = (PString *) malloc(sizeof(PString));
        str->length = &length;
        return str;
    }
    
    0 讨论(0)
提交回复
热议问题