行头->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);
}
在print_nodes()
中,不需要分配。
//struct Node* current = (struct Node*)malloc(sizeof(struct Node));
struct Node* current = head;
更好的是,从head
开始,而不是从.next
开始。
void print_nodes(const struct Node* current) {
while (current) {
printf("%d", current->data);
current = current->next
}
}
是否检查了head是否为有效指针?可能不会。
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
If(0==head) return 1;
head->data = 1;