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

后端 未结 7 1516
花落未央
花落未央 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:22

    In header file you can declare static this variable

    static struct Stack *this;
    

    And then in push method you can use this variable

    static int push(int val) {
        if(this->current_size == this->max_size - 1)
                return 0;
    
        this->data[this->current_size] = val;
        (this->current_size)++;
    
        return 1;
    }
    

    The caveat is you have to manually set this variable through some method before you want to invoke other methods, eg:

    struct Stack {
        struct Stack (*_this)(struct Stack *); // <-- we create this method
        int *data;
        int current_size;
        int max_size;
        int (*push)(int);
        int (*pop)();
    };
    

    And then we can implement _this method as

    static struct Stack *_this(struct Stack *that)
    {
        retrun this = that;
    }
    

    The example:

    struct Stack stack1, stack2;
    
    ... some initialization ...
    
    stack1->_this(&stack1)->push(0);
    stack1->push(1);
    stack1->push(2);
    
    stack2->_this(&stack2);
    stack2->push(10);
    stack2->push(20);
    

提交回复
热议问题