views:

106

answers:

2

So i have

struct node {
   int number;
   struct node *next;

 struct deck{
    int number;
    struct deck *next;
 };
};

I want to create a 2D linked list. How can i initialize something like this?

Thanks.

+2  A: 

First of all, you need to take deck outside node. What you have is valid C++ but not C.

You could write something like this:

struct node {
   int number;
   struct node *next;
};


struct deck{
   struct node* nodes;
   struct deck* next;
};
florin
I think you are missing a semicolon after struct node {...}
quinmars
The original code is "almost valid" C. Just need to name the "internal sub-struct" ... http://codepad.org/nCh96ldh
pmg
@quinmars: good eyes! Fixed it.
florin
+2  A: 

Something like this maybe ?

struct deck{
    int number;
    struct deck *next;
}
struct node {
   int number;
   struct node *next;
   struct deck *decks;
};

struct node *current_node, *new_node;
struct deck *current_deck, *new_deck;

current_node = (struct node *) malloc (sizeof(struct node));

for (i=0; i<number_of_nodes-1;i++) {
    current_deck = (struct deck* ) malloc (sizeof(struct deck));
    current_node->decks = current_deck;
    for (j=0; j<number_of_decks_in_node_i-1; j++) {
        new_deck = (struct deck* ) malloc (sizeof(struct deck));
        current_deck->next = new_deck;
        current_deck = new_deck;
    }
    new_node = (struct node *) malloc (sizeof(struct node));
    current_node->next = new_node;
    current_node = new_node;
}
Matthieu
perfect thanks! Once time limit expires ill accept answer
Matt