In c ++, nested structures of type are often used when creating trees

struct Node { struct *Node; } 

How for an object of such a structure to determine the pointer to an external object, knowing only the pointer to the internal?

  • 2
    What is an "external object"? The pointer may indicate anything of the desired type, the question is not understood. - user6550
  • I mean instance of external class. Those. created a Node a object. And then Node *c=ab . How, knowing с , to learn and? - Jonny937
  • Write in the code exactly what you want. - user6550
  • 2
    Judging by the use case, something is wrong with the logic of working with the list :) With proper organization of the case, such a desire should not arise in principle. - user6550
  • 2
    @klopp, #define container_of(ptr, type, member) ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) often used in Linux (for example, in the famous /linux/include/linux/list.h ) - avp

3 answers 3

I mean instance of external class. Those. created a Node a object. And then Node * c = ab How, knowing with, to learn and?

Use the biconnected principle - you will keep both the branches and the node's parent.

 #include <iostream> using namespace std; int counter = 0; struct Node { Node* parent; Node* left; Node* right; int value; Node( Node* p ) : Node(p, nullptr, nullptr) { } Node( Node* p, Node* l, Node* r ) { parent = p; left = l; right = r; value = counter++; } }; int main() { Node* main = new Node( nullptr, nullptr, nullptr ); main->left = new Node( main ); main->right = new Node( main ); Node* myLeft = main->left; myLeft->left = new Node( myLeft ); cout << main->value << endl; cout << main->left->value << endl; cout << main->right->value << endl; cout << main->left->left->value << endl; Node* c = main->left->left; cout << c->parent->value << endl; // зная с достучались до a, ab и a.value легко } 

    For the original structure - no way. Not at all. It is necessary either to build algorithms in this way. so that it does not interfere - either do as suggested by rikimaru2013

      If I understand the question correctly, then there are no problems here (at least for ordinary Sishnykh stratur).

      Perhaps this code:

       #include <stdio.h> #include <stdlib.h> #define container_of(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) struct Node { struct Node *node; }; struct Data { int a, b, c; struct Node link; }; int main (int ac, char *av[]) { struct Node *list; struct Data *d; list = &(((struct Data *)calloc(sizeof(*d), 1))->link); d = container_of(list, struct Data, link.node); d->a = 1; d->b = 2; } 

      something will help you.