Struct pointer with recursive

type Node struct{
content int
leftNode *Node
rightNode *Node
}

It’s not error but if I change this code like that
type Node struct{
content int
leftNode Node
rightNode Node
}
I get errors! Invalid recursive!

Are you asking why? If so, when the compiler sees:

type Node struct {
    content int
    leftNode *Node
    rightNode *Node
}

It knows the size of the struct will be

sizeof(int) + 2*sizeof(pointer)

Which on a 64-bit system is 24 bytes.

If you write:

type Node struct {
    content int
    leftNode Node
    rightNode Node
}

Then the compiler calculates the size of the Node type to be:

sizeof(int) + 2 * (
	sizeof(int) + 2 * (
		sizeof(int) + 2 * (
			sizeof(int) + 2 * (
				sizeof(int) + 2 * (
					sizeof(int) + 2 * (
						sizeof(int) + 2 * (...)))))))

Forever. The size is infinite which cannot exist, so it’s an error.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.