miqbal
miqbal

Reputation: 2227

Replace node value in a linked list

I have a linked list and a setter function.

struct my_struct {
    int    value;
    int  type;
    char   *name;
    struct my_struct *next;
};

struct my_struct *setValue(struct my_struct *s, char *name, int b) {
    if(s!=NULL) {
        while(s != NULL) {
            if( strcmp(s->name,name) == 0) {
                s->value = b;
            }
            s=s->next;
        }
        return s;
    }
    return NULL;
}

Here, name is the search keyword and b is new value of s->value. Why s->value cannot change? After that function, the output is weird. I can't understand, what happened.

Upvotes: 0

Views: 5679

Answers (3)

RedComet
RedComet

Reputation: 1202

You already got help about the loop, so I'll try whats is left.

Are you sure that both s->name and name have properly allocated memory? and that both are the same length and properly null terminated. The strcmp() function spects all this being true to give an equal response, and the allocated memory and null termination for any response at all.

If you have funny results, there is probably some memory leak somewhere. Try strncmp with a maximum character count to compare and see what happens.

Upvotes: 0

user142162
user142162

Reputation:

You need to be testing the strings equality with strcmp, as seen below. In your code, you're testing if two pointers are equal [related post].

#include <string.h>

if(strcmp(s->name, name) == 0) { // if both strings are equal
    s->value = b;
}

The location of your return statement is interesting. You're returning the address of the last item that was changed, which may be undesired.

As per @Matthew Iselin's comment, change your loop to the following:

while(s != NULL) {
    ...
}

In case you are setting the root node to the return value of the function, s will always be NULL after looping through the linked list, therefore the function will always return NULL.

Upvotes: 2

duedl0r
duedl0r

Reputation: 9424

  • String comparison like Tim explained
  • You compare the next state in your while loop, and then you handle the current state. I.e. you can't change the value of your last entry in the list, since you abort the while loop before you set the new value.

Upvotes: 1

Related Questions