Search code examples
c++structstack

Using a struct inside a struct Stack. What is wrong?


I'm trying to use a struct inside a struct Stack. The Point struct stores two members, and I want to know how to reorganize this code without using a vector or pair.

typedef struct {
    // Array to store stack elements
    int arr[MAX_SIZE];
    // Index of the top element in the stack
    int top;

    struct Point {

        int x;
        int y;
    } point;


} Stack;

Does anyone know where to start?

I'm trying to create a set of pairs with a struct (x, y). I'm working on a maze algorithm. Trying to figure out how to set up this struct/struct stack to create ordered pairs for pushing and popping.


Solution

  • A stack is just a structure to store a list of some thing. It can be any thing.

    Physically, I can stack a bunch of plates. Or papers. Or books. Or boxes, where each box holds two teddy bears.

    Same in code. Each item in a stack can be a integer, or a string, or a Student or Employee or... a point. Hence, you can create a thing:

    typedef
    struct Point
    {
        int x, y;
    }
    Point;
    

    And you can create a stack that holds that kind of thing:

    typedef
    struct Stack
    {
        Point arr[MAX_STACK_SIZE];
        int top; // -1 for empty stack
    }
    Stack;
    

    Thereafter it is easy to create/initialize a stack:

    void CreateStack( Stack * S )
    {
        S.top = -1;
    }
    

    And push a point:

    void Push( Stack * S, Point p )
    {
        if (S.top + 1 < MAX_STACK_SIZE)
            S.arr[++S.top] = p;
    }
    

    etc. User code then becomes very easy:

    int main(void)
    {
        Stack my_stack;
        CreateStack( &my_stack );
    
        Point p = { 2, 3 };
        Push( &my_stack, p );
    
        ...
    

    P.S. You can make a function to create a point, too:

    Point CreatePoint( int x, int y )
    {
        Point p = { x, y };
        return p;
    }
    

    And then use it:

        Push( &my_stack, CreatePoint( 5, 7 ) );