blackstreet23
blackstreet23

Reputation: 17

Why does the Struct *node next works for linked list in C++?

Wouldn't it be the same to just have an embedded object of the same structure that is not a pointer?

Struct Node
{
int data;
Node next;
};
//vs
Struct Node
{
int data;
Node * next;
};

Upvotes: 1

Views: 439

Answers (1)

058 094 041
058 094 041

Reputation: 496

No!

Having the following struct:

struct Node {
    Node other;
};

Is illegal! Node doesn't have a defined size; the compiler can't build it correctly. A Node would contain a Node which would contain a Node.. wait what?

A pointer however is fine, it just points to a section of memory. When defining a pointer, the type that it points to doesn't have to be complete, it just has to defined.

struct Node;

int main() {
    Node* a; // Fine, no errors.
    Node b; // Incomplete type error
}

Upvotes: 1

Related Questions