简体   繁体   中英

How to implicitly pass a *this pointer to a function pointer in struct

I write a string structure as follows.

typedef struct string string;
struct string
{
    int length;
    char* content;
    void (*init)(string*, const char*);
    void (*print)(string*);
};
void print(string* a)
{
    printf("%s", a->content);
}
void init(string* a, const char* b)
{
    a->init = init;
    a->print = print;
    a->length = strlen(b);
    a->content = (char*)malloc(sizeof(char) * strlen(b));
    strcpy(a->content, b);

}

int main()
{
    string a;
    init(&a, "Hello world!\n");
    a.print(&a);
}

I tried to mimic ooc here but I can't figure out a better way. For example, is there a possible way to make print(&a) like: a.print, without passing a pointer to itself to the function, like an implicit *this pointer does in other language?

is there a possible way to make print(&a) like: a.print, without passing a pointer to itself to the function, like an implicit *this pointer does in other language?

you cannot


warning in

 a->content = (char*)malloc(sizeof(char) * strlen(b)); strcpy(a->content, b); 

you need to allocate 1 more for the null ending char, else the strcpy writes out of the allocated block with an undefined behavior

a->content = malloc(a->length + 1);

strlen is already saved in a->length so I use it and it is useless to multiply by sizeof(char) because it is 1 by definition

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