我一直在研究一个函数 searchn()
,它接收一个链表 list
和一个字符串 lname
。
它编译得很好,但是当我尝试运行该函数时出现段错误(核心已转储)。我通过 Valgrind 运行它,它告诉我我使用的 strcpy
和 strcmp
不正确。我的 player
结构也包含在内以供引用。谁能看到我做错了什么?对不起,我不是最精通编码的。
任何帮助都会很棒。谢谢。
struct player {
char* fname;
char* lname;
char pos;
int val;
int rank;
struct player* next;
};
void searchn(struct player* list, char* lname){
while (list!=NULL && strcmp(list->lname, lname) != 0){
list = list->next;
}
if (list != NULL && strcmp(list->lname, lname)==0) {
printf("%s found! \n", lname);
printf("%s \n", list->lname);
printf("%s \n", list->fname);
printf("%c \n", list->pos);
printf("%d \n", list->val);
printf("\n");
}
}
下面是填充链表的方法。
void addp (struct player* newnode, struct player* list){
struct player* templist1;
// if the list is non empty.
if (list !=NULL){
if(newnode->pos == GOALKEEPER){ //insert if G.
while (list->next != NULL && (list->next)->rank < 1){
list = list->next;
}
templist1 = list->next;
list->next = newnode;
newnode->next = templist1;
}
if(newnode->pos == DEFENDER){// after G bef M.
// iterate through templist.
while (list->next != NULL && (list->next)->rank < 2) { // go to end of G.
// when the list isn't empty next node rank is less than one, keep going
list = list -> next;
}
// when finally rank == or > 1, then add newnode.
templist1 = list->next;
list->next = newnode;
newnode->next = templist1;
}
if(newnode->pos == MIDFIELDER){ //after G and M but before S
while (list->next != NULL && (list->next)->rank < 3) {
list = list -> next;
}
// when stopped, then add newnode.
templist1 = list->next;
list->next = newnode;
newnode->next = templist1;
}
if(newnode->pos == STRIKER){ // at the end.
while (list->next != NULL && (list->next)->rank < 4){
list = list -> next;
}
templist1 = list->next;
list->next = newnode;
newnode->next = templist1;
}
printf("player added");
}
}
最佳答案
您的 while
循环不断比较相同的两个字符串,因为它不会将列表元素中的新字符串加载到 temp 中。无论如何,您实际上并不需要临时变量。
在您当前的逻辑中,您可以将 strcpy
移动到 while
循环中:
while (list!=NULL && strcmp(temp, lname) != 0){
strcpy(temp, list->lname);
list = list->next;
}
但是你可以完全摆脱温度。改变这个:
strcpy(temp, list->lname);
while (list != NULL && strcmp(temp, lname) != 0) {
list = list->next;
}
if (strcmp(temp, lname) == 0) {
对此:
while (list != NULL && strcmp(list->lname, lname) != 0) {
list = list->next;
}
if (list != NULL) {
关于c - 在 C 中搜索链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17767794/