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

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

    The typical approach in C is to have functions expect this as the first parameter.

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

    This has the added benefit that, unless you need polymorphism, you don't need to put the functions in the stack, because you could just call push(stack, 10) instead of stack->push(stack,10).

    0 讨论(0)
提交回复
热议问题