我有一个链表和一个 setter 函数。
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;
}
这里name是搜索关键字,b是s->value的新值。为什么 s->value 不能改变?在那个函数之后,输出很奇怪。我不明白,发生了什么事。
最佳答案
您需要使用 strcmp
来测试字符串是否相等,如下所示。在您的代码中,您正在测试两个指针是否相等 [related post] .
#include <string.h>
if(strcmp(s->name, name) == 0) { // if both strings are equal
s->value = b;
}
您的 return 语句的位置很有趣。您返回的是最后更改的项目的地址,这可能是不受欢迎的。
根据@Matthew Iselin 的评论,将循环更改为以下内容:
while(s != NULL) {
...
}
如果您将根节点设置为函数的返回值,s
在遍历链表后将始终为 NULL
,因此该函数将始终返回 NULL
。
关于c - 替换链表中的节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8250386/