。这个问题通常发生在访问了未初始化或无效内存区域时。让我们逐步分析代码并找出可能的原因。首先,我们看下这段代码的结构:
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void printList(struct Node *head) { for (int i = 0; head != NULL; ++i, head = head->next) { printf("Element %d: %d\n", i, head->data); return i; // 这行代码可能导致问题 } } int main() { struct Node* head = NULL; head = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = (struct Node*)malloc(sizeof(struct Node)); head->next->data = 2; head->next->next = (struct Node*)malloc(sizeof(struct Node)); head->next->next->data = 3; printList(head); return 0; }问题出在
printList()函数中的return i;语句。这个语句导致函数在第一次迭代时就立即返回,因此循环只执行了一次。由于之后的迭代没有机会被执行,head指针并没有更新,它仍然指向原来的值。当循环试图继续执行并访问head->next->next时,就会发生段错误,因为head->next实际上并未指向有效的节点。为了解决这个问题,只需将
return i;移出for循环之外,确保整个列表被正确遍历。下面是修改后的代码:#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void printList(struct Node *head) { int i = 0; while (head != NULL) { printf("Element %d: %d\n", i, head->data); head = head->next; ++i; } } int main() { struct Node* head = NULL; head = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->next = (struct Node*)malloc(sizeof(struct Node)); head->next->data = 2; head->next->next = (struct Node*)malloc(sizeof(struct Node)); head->next->next->data = 3; printList(head); return 0; }现在,
printList()函数会在遍历完整个链表后再返回,不会引发段错误。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录