我是C语言的新手,也是编程的新手,我才刚刚开始研究链表。
static struct post {
char * str;
struct post * next;
}
head = {0, NULL};
int stringdb_add(const char * str) {
int pos = 0;
struct post * new_input = (struct post * ) malloc(sizeof(struct post));
new_input - > str = (char * ) malloc(strlen(str) + 1);
if (head.next == NULL) {
strcpy(new_input - > str, str);
new_input - > next = NULL;
head.next = new_input;
} else {
while (head.next - > next) {
++pos;
head.next = head.next - > next;
}
strcpy(new_input - > str, str);
new_input - > next = NULL;
head.next - > next = new_input;
}
return pos;
}
函数“ stringdb_add”应该返回新节点已放置的位置,但是当我测试该函数时,只会得到(00111111 ....)。
这可能是因为列表从未正确链接。
while (head.next->next) { ++pos; head.next = head.next->next; }
您正在永久更改head.next
,这肯定不是您想要的。您可能想要类似的东西:
struct post *p = &head;
while (p->next->next)
/* ... */
Nitpick:strcpy(new_input->str, str)
可以放在之前的单个位置if
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句