【发布时间】:2017-03-05 17:05:26
【问题描述】:
假设我有以下结构:
struct _node {
int id;
char *name;
struct node *next;
};
我想编写一个函数,它遍历链表并查找名称成员包含某个子字符串的结构,并将这些结构添加到新的链表并返回新的链表。
我尝试使用 strstr 执行此操作,但在某些时候我遇到了无限循环,我无法弄清楚为什么会发生无限循环。
这是我的功能:
struct _node *containSubstr(struct _node *head, char needle[]) {
if (head == NULL) {
printf("BLOOP BLEEP BOOP BEEP.\n");
exit(EXIT_FAILURE);
}
struct _node *curr = head;
struct _node *returnHead = createEmptyNode();
while (curr != NULL) {
char haystack[strlen(curr->name)];
strcpy(haystack, curr->name);
strToLower(needle);
strToLower(haystack);
if (strstr(haystack, needle) != NULL) {
// this is where I get the infinite loop
append(returnHead, curr);
}
curr = curr->next;
}
return returnHead;
}
函数 append 和 createEmptyNode 已经过测试并且工作正常。
我多次检查了这个逻辑,我认为这必须有效。我用打印语句填充了我的代码,似乎在它找到包含子字符串的所有节点之后它不断重复最后一个节点并进入无限循环。
这是我的附加功能:
void append(struct _node *head, struct _node *newNode) {
if (head == NULL) {
printf("BLOOP BLEEP BOOP BEEP.\n");
exit(EXIT_FAILURE);
}
struct _node *curr = head;
if(curr == NULL) {
head = newNode;
}
else {
while(curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
【问题讨论】:
-
The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character. -
我修复了这个问题,但仍然出现无限循环。
-
你的最后一个元素是否指向
null,这是下一个明显的问题。 -
显示你的
createEmptyNode -
在
append函数中,第二个if语句永远不会执行。
标签: c string linked-list