【发布时间】:2018-11-23 04:34:39
【问题描述】:
任务是创建一个由对象组成的链表。用户在main 中为每个Node 输入数据,然后将对象传递给push,从而创建列表。
问题出在printList 函数中,其中break 的条件从未满足。
出于某种原因,head = head->next 行没有做任何事情,因为每次迭代时next 的地址都保持不变。
typedef struct Node {
int a;
char asd[30];
struct Node *next;
}Node;
Node *head = NULL;
void push(Node**head, struct Node* object);
void printList(Node *head);
int main() {
struct Node {
int oA;
char oAsd[30];
struct Node *next;
};
struct Node *object = malloc(sizeof(struct Node));
int c = 0;
while (1) {
printf("This int will be stored in Node %d.\n", ++c);
scanf("%d", &object->oA);
getchar();
if (!object->oA) {
break;
}
printf("This string will be stored in Node %d.\n", c);
gets_s(object->oAsd, 30);
if (!(strcmp(object->oAsd, "\0"))) {
break;
}
push(&head, object);
}
printList(head);
return 0;
}
void push(Node ** head, struct Node* object)
{
Node *tmp = malloc(sizeof(Node));
tmp = object;
tmp->next = (*head);
(*head) = tmp;
}
void printList(Node *head) {
if (head == NULL) {
puts("No list exists.");
exit(9);
}
while (1) {
printf("-------------------------------\n");
printf("|Int: <%d> |||| String: <%s>.|\n", head->a, head->asd);
printf("-------------------------------\n");
if (head->next) {
printf("\n\n%p\n\n", head->next);
head = head->next;
}
else {
break;
}
}
}`
【问题讨论】:
-
为什么要在
main中重新定义struct Node? -
tmp = malloc(...); tmp = ...是内存泄漏。 -
这几乎没有回答我的任何问题。
-
您的程序中有两种不同的结构类型。出于某种原因,您将它们都命名为
Node,但它们仍然是不同的类型。 -
tmp = object;==>*tmp = *object
标签: c loops linked-list