LinkList In C;分段故障

时间:2016-02-26 23:16:02

标签: c linked-list

我在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 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

正如评论中所提到的,问题在于:

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

您正在使用temp->data的值(由于malloc返回未初始化的内存而未知)并将其视为指针。所以scanf写入一些未知的内存位置,导致核心转储。

您希望使用address-of运算符&来传递此变量的地址:

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