Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dealing with array of linked list

My approach:

An array of fixed-length (lets say 20) each element is pointer to the first node of a linked list. so i have 20 different linked list.

This is the structure:

struct node{
       char data[16];
       struct node *next;
};

My declaration for that array

struct node *nodesArr[20];

now to add a new node to one of the linked list, i do this:

struct node *temp;

temp = nodesArr[i]; // i is declared and its less than 20
addNode(temp,word); // word is declared (char *word) and has a value ("hello")

The addNode function:

void addNode(struct node *q, char *d){
    if(q == NULL)
        q = malloc(sizeof(struct node));
    else{
        while(q->next != NULL)
            q = q->next;

        q->next = malloc(sizeof(struct node));
        q = q->next;
    }

    q->data = d; // this must done using strncpy
    q->next = NULL; 
}

and to print data from the array of linked list, i do this:

void print(){
    int i;
    struct node *temp;

    for(i=0 ; i < 20; i++){
        temp = nodesArr[i];
        while(temp != NULL){
            printf("%s\n",temp->data);
            temp = temp->next;
        }
    }
}

now compiler gives no error, the program run and i pass the data to it, and when i call print it doesn't print any thing,,??

UPDATE::

after I edited the code (thx for you), i think the problem in the print function,, any idea ?

like image 356
Rami Jarrar Avatar asked Feb 09 '11 00:02

Rami Jarrar


2 Answers

The problem lies in addNode(). When the list is empty you do:

q = malloc(sizeof(struct node));

but the scope of q is limited to addNode(). You should have declared addNode() as

void addNode(struct node **q, char *d)

and adjust your code accordingly:

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

and so on...

like image 94
thkala Avatar answered Oct 18 '22 22:10

thkala


When you pass struct node *q to addNode you are giving it an address for an element in your array. If you use malloc inside, then you are overwriting this variable q, which is local to the function and now points to something different, but you haven't changed your original array. Try using a pointer to pointer to node (struct node **q).

like image 3
Jacobo de Vera Avatar answered Oct 18 '22 21:10

Jacobo de Vera