简体   繁体   中英

nested structs and pointers

I am learning about nested structures and came across the following code:

// Stack.h

#ifndef STACK_H
#define STACK_H

struct Stack{
    struct Link{
        void* data;
        Link* next;
        void initialize(void* dat, Link* nxt);
    }* head;
    void initialize();
    void push(void* dat);
    void* peek();
    void* pop();
    void cleanup();
};

#endif // STACK_H

the Link structure is within the scope of Stack and to access Link I would have to use Stack::Link.

I am a bit confused about the pointer head that is declared after the } to close the Link struct.

Does this mean that there is a Link pointer variable named head inside the Stack scope?

What is the effect of defining the head pointer as:

};
Link* head;

vs

}* head; //as per the code above?

There is no difference. Both declarations result in a Stack::head member of type Stack::Link* .

Does this mean that there is a Link pointer variable named head inside the Stack scope?

Yes, that's exactly right.

As to your second question, there is no semantic difference between the two styles of declaration.

Its just a short hand for the semantic. like how we use += . And yes you have a local pointer variable.

struct Stack{
    struct Link{
        void* data;
        Link* next;
        void initialize(void* dat, Link* nxt);
    };

    Link* head;  //Same as code as in your program
    void initialize();
    void push(void* dat);
    void* peek();
    void* pop();
    void cleanup();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM