1

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?

sz ppeter
  • 1,698
  • 1
  • 9
  • 21
  • Note that e.g. C++ does not store pointers to methods in every single object. C++ does something more like `obj->vtable->print(obj)` (where the vtable is static and shared among all instances of this class). Also, your `a` is not a pointer, so C++ would compile this down to a simple function call (`print(&a)`). – melpomene Mar 16 '19 at 07:43
  • See also https://stackoverflow.com/q/351733/1848654, https://stackoverflow.com/q/415452/1848654, https://stackoverflow.com/q/3072499/1848654. – melpomene Mar 16 '19 at 08:11

1 Answers1

0

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

bruno
  • 32,421
  • 7
  • 25
  • 37
  • Even not possible for using macro? – sz ppeter Mar 16 '19 at 19:35
  • @szppeter if using a macro you have anyway to specify on what _print_ applies, so to give it in param like on `#define pr(x) x.print(&x)` and a use is `pr(a)` so is like a standard function call – bruno Mar 16 '19 at 19:54
  • I am thinking to make something like: #define X.print X.print(&X), or more general to be: #define X.Z(Y) Z(&X,Y) , therefore, whenever I call object X to do something, it always pass a pointer to itself to the function, but it turns out, I can't put a dot in macro – sz ppeter Mar 16 '19 at 20:08
  • @szppeter but cannot work, sorry but you cannot mimic C++ in C, just do C++ ;-) – bruno Mar 16 '19 at 20:10