2016-02-26 88 views
0

我在C中創建這個程序,linkelist從用戶處獲取輸入,只是爲了創建一個節點並將頭指向該節點並打印該節點元素的值和地址。我在運行時遇到了分段錯誤,請幫我解決問題。LinkList In C;分段錯誤

#include<stdio.h> 
#include<stdlib.h> 

struct Node { 
    int data; 
    struct Node* next; 
}; 

struct Node* head; 

void main() { 
    head = NULL; 
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); 
    printf("Enter the number you want in node\n"); 
    scanf("%d",(int *)temp->data); 
    temp->next = NULL; 
    head = temp; 
    printf("the address of node is %p",head); 
    printf("the value is %d",temp->data); 
} 
+2

'的scanf( 「%d」,(INT *)TEMP->數據);' - >'scanf(「%d」,&temp-> data);' – BLUEPIXY

+0

錯誤:'>'令牌之前的預期表達式 scanf(「%d」,(int *)temp-> data); - > scanf (「%d」,&temp-> data); –

+0

謝謝@BLUEPIXY它帶有&temp->數據,:) –

回答

0

正如在評論中提到的,問題就在這裏:

scanf("%d",(int *)temp->data); 

你正在做的temp->data值(因爲malloc返回未初始化的內存是未知的),並把它當作一個指針。所以scanf寫入一些未知的內存位置,導致核心轉儲。

你想而不是使用地址的運營商&通過這個變量的地址:

scanf("%d", &temp->data); 
1
//try this code 
#include<stdio.h> 
#include<stdlib.h> 
struct Node { 
    int data; 
    struct Node* next; 
}; 
struct Node* head; 

void main() { 
    head = NULL; 
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); 
    printf("Enter the number you want in node\n"); 
    scanf("%d",&temp->data); 
    temp->next = NULL; 
    head = temp; 
    printf("the address of node is %p",head); 
    printf("the value is %d",temp->data); 
}