2016-02-26 61 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); 
}