0
我遇到分段錯誤,我不知道問題出在哪裏。鏈接列表分段故障
#include "stdio.h"
#include "stdlib.h"
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
struct node * curr;
struct node * newNode;
void createList(){
int data,n , i ;
scanf("%d",&n);
for (i = 0 ; i < n ;i++){
scanf("%d",&data);
curr = head;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data=data;
newNode->next=NULL;
if (curr == NULL){
head = newNode;
}else
while (curr->next != NULL){
curr = curr->next;
}
curr->next = newNode;
}
}
int main(int argc, char const *argv[])
{
createList();
return 0;
}
請問你能弄清楚哪裏? 第一次迭代很好,但當i = 1
時,出現錯誤。
調試器在哪裏指出問題? – jxh
[不要強制轉換'malloc()']的返回值(http://stackoverflow.com/a/605858/1983495)。 –