views:

47

answers:

5

I have the following struct:

struct cell {
    int nmbr;
    struct cell *p;
};

I have created a chain of linked structs from this type. Every struct is connected to its predecessor through *p. If I decide to print all nmbrs with a recursive algorithm as shown below, how do I define the stop condition?

void write(struct cell* l) {
    /* The following if statement doesn't solve my problem,
       but hopefully you see what I'm trying to do */
    if (&l != 0x000000) {
        printf("%d \t", l->nmbr);
        write(l->p);
    }
}
A: 

the print number up here, for the current node.

if(l->p!=NULL)
write(l->p);

Chris H
the reason for this is l is a pointer, you need to check to see if the pointer value is null, not the pointer to the pointer value.
Chris H
This doesn't handle the case where `write()` is passed `NULL` directly rather than in a recursive call.
Nick Meyer
except that the only way that could happen is if the user calls it with null directly. Even if the print was inside the if a user could simply pass a bad non-null reference, so it doesn't really make the program safer.
Chris H
+3  A: 

You want

if (l != 0)

or

if (l != NULL)

Of course, you also need to make sure that the tail of your linked list has p assigned NULL as well; otherwise it will be uninitialized and probably something not NULL but invalid anyway.

Nick Meyer
+1  A: 

Assuming the linked list is not cyclic, you just stop when you reach a null pointer. Change

if (&l != 0x000000)

to

if (l != NULL)
nos
+2  A: 

You should check against 'l' not being NULL rather than '&l' assuming that the linked list in NULL terminated.

Jay
+1  A: 

As others have said, you should check l (el), not &l, against 0 or NULL. So, your function should look something like:

void write(CELL* l) {
    if (l != 0x000000) {
        printf("%d \t", l->nmbr);
        write(l->p);
    }
}

That said, it is easy to accomplish the same thing using a while, thus avoiding the overhead of recursion:

  list_pos = list_head;
  while (list_pos != NULL) {
    printf("%d \t", list_pos->nmbr);
    list_pos = list_pos -> p;
  }
GreenMatt