“this” pointer in C (not C++)

后端 未结 7 1524
花落未央
花落未央 2020-12-24 09:42

I\'m trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop()

7条回答
  •  臣服心动
    2020-12-24 10:19

    There's no implicit this in C. Make it explicit:

    int push(Stack* self, int val) {
        if(self->current_size == self->max_size - 1)
                return 0;
    
        self->data[self->current_size] = val;
        (self->current_size)++;
    
        return 1;
    }
    

    You will of course have to pass the pointer to the struct into every call to push and similar methods.

    This is essentially what the C++ compiler is doing for you when you define Stack as a class and push et al as methods.

提交回复
热议问题