How come this works?

This is a discussion on How come this works? within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <stdlib.h> struct node { void *data; struct node *next; }; struct node *rootp = NULL; void ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    How come this works?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    struct node {
        void *data;
        struct node *next;
    };
    
    struct node *rootp = NULL;
    
    void append(char *str)
    {
        struct node *newnode = malloc(sizeof(struct node));
    
        newnode->data = str;
        newnode->next = NULL;
    
        if (rootp == NULL)
            rootp = newnode;
    
        else {
            struct node *walker = rootp;
    
            while (walker->next != NULL)
                walker = walker->next;
    
            walker->next= newnode;
        }
    }
    
    void mostrar_lista(void)
    {
        struct node *walker = rootp;
    
        while (walker != NULL) {
            printf("%s\n", walker->data);
            walker = walker->next;
        }
    }
    
    int main(void)
    {
        append("foo");
        append("bar");
        append("C!");
    
        mostrar_lista();
    
        return 0;
    }
    foo, bar, and C! are not copied to anywhere so how can I point to something that "doesn't exist"?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    String literals do exist.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can anybody show me why this works??
    By tzuch in forum C Programming
    Replies: 2
    Last Post: 03-29-2008, 09:03 AM
  2. fprintf works in one function but not in the other.
    By smegly in forum C Programming
    Replies: 11
    Last Post: 05-25-2004, 03:30 PM
  3. Works only part of the time?
    By scr0llwheel in forum C++ Programming
    Replies: 1
    Last Post: 01-07-2003, 07:34 PM
  4. Programs works one way, not another. VC++ 6.0 help.
    By Cheeze-It in forum Windows Programming
    Replies: 4
    Last Post: 12-10-2002, 09:29 PM
  5. it never works...
    By Ryce in forum Game Programming
    Replies: 5
    Last Post: 08-30-2001, 07:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21