【发布时间】:2013-07-20 00:29:17
【问题描述】:
我一直在研究一个函数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");
}
}
【问题讨论】:
-
您将需要展示如何在链接列表元素中分配和分配值。该逻辑可能有问题导致您的分段错误。
-
我猜是这样,但问题是填充链表的方法到目前为止工作正常。我有另一种搜索方法,它搜索每个节点的
int val,恰好可以正常工作。 -
您仍然需要展示如何分配字符串和结构,以便全面了解正在发生的事情。以及如何将字符串复制到结构中。其中任何一个都可能产生分段错误。
-
我实际上碰巧弄明白了。我没有传递
char*,而是传递了char[]。一旦改变,段错误就消失了。感谢大家的帮助。
标签: c search linked-list strcmp strcpy