Thread: First Time Using Linked Lists, Having Trouble Replacing First Node

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Ah, well that's simple. You aren't passing a pointer-to-pointer for your replace_words function. You can't change what the first node points to, because the replacement is lost when the function ends, because you can't change that pointer.


    Quzah.
    Hope is the first step on the road to disappointment.

  2. #2
    Registered User
    Join Date
    Jan 2006
    Location
    Seattle
    Posts
    30
    Quote Originally Posted by quzah
    Ah, well that's simple. You aren't passing a pointer-to-pointer for your replace_words function. You can't change what the first node points to, because the replacement is lost when the function ends, because you can't change that pointer.


    Quzah.
    That makes sense... it also made a little light click on in my head.

    Currently when I'm replacing words I free() my string and then the node which is completely unnecessary I'm assuming. All I need to free is the string and then malloc another the size of what I need... doh.

    After dinner I'll get on that but I'm fairly certain it'll work.

    Thanks for your help!

    -Peter

    **EDIT**

    Yeah that did it. That original monstrocity is now cut down to this.

    Code:
    int replace_words(WordNode *words, const char *oldword, const char *newword)
    {
    	WordNode *temp = find_word(words, oldword);
    
    	while(temp)
    	{
    		free(temp->word);
    		temp->word = (char *)malloc(strlen(newword) + 1);
    
    		if(!temp->word)
    			return ERROR;
    
    		strcpy(temp->word, newword);
    		temp = find_word(words, oldword);
    	} /* end while(temp) */
    
    	return 0;
    }
    Thanks again, seems like it always ends up being that I try and make things harder than they really are.
    Last edited by Peter5897; 06-16-2006 at 09:33 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Help here with qsort!
    By xxxrugby in forum C Programming
    Replies: 11
    Last Post: 02-09-2005, 08:52 AM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 10:16 AM
  5. struggling with linked lists
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 01-31-2002, 07:01 AM