Thread: Error in linking nodes

  1. #1
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463

    Error in linking nodes

    When I allocate nodes and copy a string (passed from another function) into the nodes it seems to work fine, all strings are copied into different nodes, however the last string in the last node doesn't seem to attach to the list, hence when I return the head and then try printing it out later, the last string is missing, because the last node never attached, I don't see why that is happening.

    Code:
      node = makeNode();
      node->text = malloc (len * sizeof(char));
    
      if (head == NULL) {
        head = node;
        tail = node;
        strcpy(head->text, string);
        printf("%s\n", head->text;
        N++;
      }
      else {
        tail->next = node;
        prev = tail;
        next = node;
        tail = tail->next;    
        strcpy(tail->text, string);
        printf("%s\n", tail->text;
        N++;
      }
      return (head);
    =========================================
    Everytime you segfault, you murder some part of the world

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Should that not be strcpy(node->text, string) instead? Node is the new thing, not tail. Edit:--No never mind, you set tail right before that line.

    In that case, I'd bet five cents that your routine to print has while(node->next!=NULL) instead of while(node!=NULL).

  3. #3
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463
    Quote Originally Posted by tabstop View Post
    Should that not be strcpy(node->text, string) instead? Node is the new thing, not tail. Edit:--No never mind, you set tail right before that line.

    In that case, I'd bet five cents that your routine to print has while(node->next!=NULL) instead of while(node!=NULL).
    Dang...you're good.

    Just remember that. Thanks =D

    Here's $20
    =========================================
    Everytime you segfault, you murder some part of the world

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double Linked List Sorting
    By algatt in forum C Programming
    Replies: 5
    Last Post: 09-15-2007, 12:41 PM
  2. Programmatically creating nodes in a treeview problem
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 10-12-2006, 02:41 PM
  3. interchange nodes in a linked list
    By Gustavo in forum C++ Programming
    Replies: 0
    Last Post: 10-26-2004, 07:14 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM