C에서 단일 연결 목록을 구현하기위한 코드를 작성했습니다. 코드가 컴파일되는 동안 코드를 실행하려고 할 때 세그멘테이션 오류가 발생합니다.C - 세그먼트 화 오류 오류의 단일 연결 목록 프로그램
코드입니다 :
#include <stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void InsertAtPosition(int data, int n){
int i;
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node*));
temp1->data = data;
temp1->next = NULL;
if(n == 1){
temp1->next = head;
head = temp1;
return;
}
struct Node* temp2 = head;
for(i=0; i<n-2; i++){
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
void Print(){
struct Node* temp = head;
printf("List is: \n");
while(temp != NULL){
printf("\t%d\n", temp->data);
temp = temp->next;
}
}
int main(){
head = NULL;
InsertAtPosition(10, 1);
InsertAtPosition(11, 2);
InsertAtPosition(12, 3);
Print();
return 0;
}
코드는 오류 Segmentation fault (core dumped)
을주고있다.
정확히 무엇을하고 있습니까?
말해봐? –
목록이 비어있을 때 위치 10에 어떻게 삽입 할 수 있습니까? – user3386109
'struct Node * temp1 = (struct Node *) malloc (sizeof (struct Node *)); 틀린. – EOF