# nested structures: pointer to outer object

Trees often use nested structures of this type:
struct Node{
struct *Node;
}
I have an object with such structure with arbitrary number of levels.
How can I determine a pointer to an outer object for a given inner object?
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
struct *Node;
that is wrong syntax.

correct is:

``````struct Node
{
SomeType value;
Node * pnext;
};
``````

from name pnext you may see what's the purpose of this construction. you have a Node structure (object) which is pointing to another Node element or to nothing if pnext is NULL.

therefore 'node' structures always are elements of a linked list or a linked tree:

``````struct TreeNode
{
std::string name;
int val;
TreeNode * pParent; // points up
TreeNode * pPrev;     // points left
TreeNode * pNext;     // points right
TreeNode * pFirstChild; // points left-down
TreeNode * pLastChild;  // points right-down
int GetLevel() { for (int n = 0, TreeNode * p = pParent; p != NULL; ++n, p = p->Parent); return n; }
};
``````

from the GetLevel member function you see how you can determine the current 'level' in hierarchy. however for a single linked list with a node element that has only a forward pointer, you only can determine how many nodes are left to the end. to determine the current level of the node, you would need to start with the head node and loop until pnext equals to the current 'this' pointer.

Sara

Experts Exchange Solution brought to you by