How to Implement stack by function pointer and how to use it [closed]

No, function members cannot be declared in C structs (only in C++). The convention is to pass the struct pointer as the first argument in the functions when doing object oriented programming. Also, C++ really does the same thing, the “this” pointer is passed as the first argument, it is just hidden.

struct stack{
  int[10] data;
  int top;
};

void stack_init(struct stack* stack);          
int stack_isEmpty(struct stack* stack);           
int stack_isFull(struct stack* stack);            
void stack_push(struct stack* stack, int ivalue);
int stack_pop(struct stack* stack);

This part below may be more than what you are asking for but if you want the functions to be more “dynamic”, you can put function pointers in the struct to make them “changeable”, i.e. to simulate the virtual keyword in c++.

struct stack{
    int[10] data;
    int top;
    int (*isEmpty)(struct stack* stack);           
    int (*isFull)(struct stack* stack);            
    void (*push)(struct stack* stack, int ivalue);
    int (*pop)(struct stack* stack);
};

int stack_isEmpty1(struct stack* stack);           
int stack_isFull1(struct stack* stack);            
void stack_push1(struct stack* stack, int ivalue);
int stack_pop1(struct stack* stack);

void stack_init1(struct stack* stack)
{
    stack->isEmpty = &stack_isEmpty1;
    stack->isFull = &stack_isFull1;
    stack->push = &stack_push1;
    stack->pop = &stack_pop1;
    ...
}

int stack_isEmpty2(struct stack* stack);           
int stack_isFull2(struct stack* stack);            
void stack_push2(struct stack* stack, int ivalue);
int stack_pop2(struct stack* stack);

void stack_init2(struct stack* stack)
{
    stack->isEmpty = &stack_isEmpty2;
    stack->isFull = &stack_isFull2;
    stack->push = &stack_push2;
    stack->pop = &stack_pop2;
    ...
}

So now if you have 2 stack objects, initialized with stack_init1 and stack_init2 respectfully, they each will call their own sets of functions. Example:

struct stack* a, b;
stack_init1(a);
stack_init2(b);

/* This will call stack_isEmpty1*/
a->isEmpty(a);

/* This will call stack_isEmpty2*/
b->isEmpty(b);

Leave a Comment