gpt4 book ai didi

c - 使用 'for' 并将指针作为循环变量时的无限循环

转载 作者:行者123 更新时间:2023-11-30 14:45:46 24 4
gpt4 key购买 nike

我对编码很陌生,并且遇到了一个问题。我尝试自己解决这个问题,并进行了很多谷歌搜索,但我仍然没有解决方案。也许你们中的一个人可以帮忙?

这是我的代码:

int main(int argc, char **argv) {
struct node {
char *str;
int count;
struct node *next;
};

struct node head = { argv[1], 1, NULL };
for (int i = 2; i < (argc); i++) {
for (struct node *p = &head; (p != NULL); p = p->next) {
printf("%s,%s\n", argv[i], p->str);
if (strcmp(argv[i], p->str) == 0) {
printf("case1\n");
p->count++;
break;
}
else if ((strcmp(argv[i], p->str) != 0) && p->next) {
printf("case2\n");
printf("Adresse, auf die p zeigt: %p", &p);
continue;
}
else if ((strcmp(argv[i], p->str) != 0) && (!p->next)) {
printf("case3\n");
struct node *oldhead = &head;
head.str = argv[i];
head.count = 1;
head.next = oldhead;
break;
}

}
}

// Print how many times each string appears

return 0;
}

目标是创建一个链表,其中包含调用程序时向 main() 提供的所有参数。如果有重复项,结构应该对它们进行计数。例如,如果我像 ./a.out foofoo foo 这样调用程序,结果应该是长度为 2 的列表,其中第一个元素包含字符串 "foo" 并计数 2,第二个元素包含字符串 "fool" 并且计数为 1。问题在于内部 for 循环中的 else if 语句。这是唯一应该实际使用内部 for 循环并将 p->next 分配给 p 的部分。不幸的是,这并没有发生。结果是内部 for 循环一遍又一遍地开始,并且指针 p 始终指向同一个地址(我使用 printf 来解决这个问题)。

你们中有人知道这里可能出现什么问题吗?我尝试了一切,并试图在网上寻找解决方案......

非常感谢!!!

最佳答案

问题出在这部分代码

   else if ((strcmp(argv[i], p->str) != 0) && (!p->next)) {
printf("case3\n");
struct node *oldhead = &head;
head.str = argv[i];
head.count = 1;
head.next = oldhead;
break;
}

您需要分配一个新的结构,然后将其地址放入最后一个结构条目中。

       else if ((strcmp(argv[i], p->str) != 0) && (!p->next)) {
printf("case3\n");
struct node *oldhead = p;
p = (struct node *) malloc(sizeof(node));
if (p == NULL) { .... manage the error ... }
oldhead->next = p;
p->str = argv[i];
p->count = 1;
p->next = NULL;
break;
}

现在您正在创建节点并将它们串在一起。您之前有效地更新了同一个节点

关于c - 使用 'for' 并将指针作为循环变量时的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com