2014-09-27 47 views
1
#include <stdio.h> 
#include <stdlib.h> 

typedef struct node_struct { 
    int data; 
    struct node_struct *next; 
} node; 

typedef node *list; 


int main() 
{ 
    int temp; 
    list head , tempList; 
    char cont = 'Y'; 
    head = NULL; 

    do { 
     printf("Enter Data\n"); 
     scanf("%d",&temp); fflush(stdin); 
     tempList = (list)malloc(sizeof(node)); 
     tempList->data = temp; 
     tempList->next = head->next; // This line has error 
     head->next = tempList; 
     printf("Do you wish to continue (Y/N)\n"); 
     scanf("%c", &cont); fflush(stdin); 
    } while (cont == 'Y'); 

    return 0; 
} 

程序接收到的信號SIGSEGV,分段錯誤。 0x08048516 in mainself()listself.c:24c程序列表訪問值分段錯誤

我想將指針指向最新的輸入值。但head-> next給我分段錯誤。

我的問題是我如何實現這個邏輯?

user input 1 : 5 
user input 2 : 6 
user input 3 : 3 

和列表的內部結構像

頭 - > 3 - > 6 - > 5

此外while循環取入值CONT之前剛剛退出。可以用它來代替「\ n」。任何解決方案?

+0

'head-> next'是no的地址,因爲head本身爲null,然後將它分配給templist-> next。 – 0decimal0 2014-09-27 13:44:28

+0

請讓我知道,如何在上面的代碼中初始化head-> NULL旁邊? – yantrakaar 2014-09-27 14:04:41

回答

2

頭只是一個指針,並沒有指向任何內存,所以你不能取消引用它。

首先,您必須將tempList的 - > next值設置爲NULL。

tempList->next = NULL ; 

然後,你必須改變你使用頭的方式。

tempList->next = head; // point it to NULL or the head 
head = tempList; // tempList becomes the new head 
+0

是的,但如果我這樣做,那麼如果用戶輸入5,6,3,那麼我的內部結構將像5 - > 6 - > 3 - >頭?對 ? – yantrakaar 2014-09-27 14:02:13

+0

@ yantrakaar不,它會完全顛倒。頭 - > 3-> 6 ...並注意頭是一個指針,而其他的是結構。 – 2501 2014-09-27 14:02:49

+0

你能評論這個嗎?此外,while循環在獲取cont的值之前剛剛退出。可能需要「\ n」。任何解決方案? – yantrakaar 2014-09-27 14:07:16

4

在引用它之前,您需要分配head

此外,在將tempList->next設置爲head->next之前,您需要將head->next設置爲一個值。

所以......

head = (list)malloc(sizeof(node)); 
tempList = (list)malloc(sizeof(node)); 
head->next = NULL; 
head->next = tempList; 
tempList->data = temp; 
+0

完全+1,相當快答案:) – 0decimal0 2014-09-27 13:45:20

+0

確切地說,我問我如何初始化head->旁邊的NULL,以便程序正常工作。 – yantrakaar 2014-09-27 13:57:21

+0

你能評論這個嗎?此外,while循環在獲取cont的值之前剛剛退出。可能需要「\ n」。任何解決方案? – yantrakaar 2014-09-27 14:08:57

0

你套頭爲null,所以你當然會獲得一個段錯誤。你需要像你做tmpList一樣初始化頭部。