drum
drum

Reputation: 5651

Struct inside of same struct type?

How can I have struct that contains a type of itself.

struct node { struct node *nodes[MAX]; int ID; };

struct node *node1, *node2;
node1 = (struct node*) malloc(sizeof(struct node));
node2 = (struct node*) malloc(sizeof(struct node));
node1->ID = 1;
node2->ID = 2;
node1->nodes[0] = node2;
node2->nodes[0] = node1;

There are no errors but the program doesn't execute correctly.

EDIT: I've added more of my code.

FINAL: It was a mistake in my part that I created an infinite recursion. I'll proceed to delete this threat. Sorry for your time spent.

Upvotes: 0

Views: 9873

Answers (2)

paddy
paddy

Reputation: 63471

That's because you are storing an array of pointers to the struct. That's quite different.

You can't have the same struct inside itself. That would be an infinitely recursive definition.

Now, if you would show more of your program we may be able to help you understand why your program doesn't run the way you expect. Chances are you have not initialised the pointers because of confusion over exactly what they are.

[edit] Now that you have posted some code, and ignoring that you haven't said exactly what is going wrong, I expect that you are trying to iterate over the entire pointer list while examining your graph, but you never initialised it.

When you malloc, the memory will be uninitialised. Standard practice in C is to use calloc instead which will set all bytes to zero. Since you seem to be using the nodes array as a list, you may want to add a num_edges field to the node and make a function to do a two-way join on two nodes.

struct node {
    int num_edges;
    struct node *nodes[MAX];
};

int join( struct node *a, struct node *b )
{
    if( a->num_edges >= MAX || b->num_edges >= MAX ) return 0;
    a->nodes[a->num_edges++] = b;
    b->nodes[b->num_edges++] = a;
    return 1;
}

You could also test whether there is an edge from a to b like this:

int has_edge( struct node *a, struct node *b )
{
    int i;
    for( i = 0; i < a->num_edges; i++ ) {
        if( a->nodes[i] == b ) return 1;
    }
    return 0;
}

Upvotes: 4

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Your code is perfectly valid - having pointer to the same struct inside the struct is ok.

Upvotes: 1

Related Questions