C中的分段错误编译错误

时间:2018-02-14 14:31:52

标签: c linked-list

Node* Insert(Node *head,int data)
{
 // Complete this method
   Node *temp, *temp1;
   temp1 = head;
   temp = (Node *)malloc(sizeof(Node));
   temp->data = data;
   temp->next = NULL;
   while(temp1->next!=NULL){
       temp1 = temp1->next;
   }
   temp1->next = temp;
   return head;
}

我正在尝试编写简单的代码以插入数组的末尾。该方法适用于GCC编译器,但在使用HackerRank上的在线编译器进行编译时会出现分段错误错误。对于不同的编译器,程序的工作方式是否不同

1 个答案:

答案 0 :(得分:2)

关注我的评论:第一种情况,当链表为空时,head将为NULL。因此,如果head为null,则添加一个条件以将temp分配给head

<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>disabled</IISExpressWindowsAuthentication>