c - C 中的链表;分段故障

标签 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);
}

最佳答案

//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);
}

关于c - C 中的链表;分段故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35663468/

相关文章:

c - 从文件中读取位并将其存储到 C 中的 char 数组中

java - 该方法必须返回 Object 类型的结果

java - 在链表末尾插入并不是一个特殊情况。那么数组的末尾呢?

c++ - 如何在 C/C++ 中捕获 system() 的结果

c - 链接列表不打印列表

c++ - 需要使用 Book* head 变量重载运算符但不起作用

C++ - 使用 std::list,如何打印对象私有(private)成员的链表?

C 中的组合前增量和后增量

c - 关于不兼容指针类型的警告

c - 获取 DRAM 或 SRAM galaxy S7 的起始地址