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.
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].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:
In case you are setting the root node to the return value of the function,
swill always beNULLafter looping through the linked list, therefore the function will always returnNULL.