【发布时间】:2023-03-17 00:18:02
【问题描述】:
行头->data = (int)1; ,抛出上述异常 - 抛出未处理的异常:写访问冲突。头是 0xFFFFFFFFCBB1E630。可能是什么原因?
#include <stdio.h>
#include <conio.h>
void print_nodes(struct Node* head);
struct Node {
int data;
struct Node* next;
};
void print_nodes(struct Node* head) {
struct Node* current = (struct Node*)malloc(sizeof(struct Node));
while (current->next != NULL) {
printf("%d", current->data);
}
}
void main() {
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* first = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = first;
first->data = 2;
first->next = second;
second->data = 3;
second->next = NULL;
print_nodes(head);
}
【问题讨论】:
-
current的意义何在?只需使用head。current->next未初始化。 -
修复后,
while (current->next != NULL)将在current->next != NULL时无限循环。应该是struct Node* current = head,在循环内是current = current->next。或者,直接在print_nodes()中使用head,因为它是列表头部的副本。 -
在不包含
<stdlib.h>和<malloc.h>的情况下如何编译? -
谢谢。你们都是对的。我必须分配 struct Node* current = head;并运行 while (current) 。我不再收到错误消息了。
标签: c