收集2 : fatal error:/usr/local/bin/gnm returned 1 exit status

标签 c pointers linked-list

我写了一个链接列表

In [69]: !cat linked_list.cpp                                                                                                                         
//linked list: inserting a node at beginning
#include <stdlib.h>
#include <stdio.h>
struct Node {
    int data;
    struct Node *next;
};
void insert(int x);
void print();
struct Node *head; //global variable, can be accessed anywhere
int main() {
    head = NULL; //empty list
    printf("How many numbers?\n");
    int n,i, x;
    scanf("%d", &n);
    for (i=0; i<n; i++) {
        printf("Enter the number \n");
        scanf("%d", &x);
        insert(x);
        print();
    }
}

void insert(int x) {
    Node *temp = (Node*) malloc(sizeof(struct Node));
    (*temp).data = x;
    (*temp).next = NULL;
    head = temp;//insert to the head
    if (head != NULL) (*temp).next = head;
    head = temp;
}

void print() {
   struct Node *temp = head;
   printf("List is: ");
   while(temp != NULL)
   {
       printf(" %d", (*temp).data);
       temp = (*temp).next;
    }
   printf("\n");
}

尝试运行但收到错误报告:

gcc linked_list.cpp                                                                                                                         
collect2: fatal error: /usr/local/bin/gnm returned 1 exit status
compilation terminated.

gcc 提供了一些有用的提示。

我的代码有什么问题?

最佳答案

当您有一个指向结构的指针时,就像 insert() 中的 temp 的情况一样,而不是执行类似的操作

(*temp).data

您可以使用箭头运算符并执行以下操作

temp->data
<小时/>

由于这是一个C程序,因此在声明结构体Node的结构体变量时,必须使用

struct Node var_name;

而不是

Node var_name;

在 C 语言中,最好不要显式转换 malloc() 的返回值。 请参阅this .

因此将 insert()temp 的声明更改为

struct Node *temp = malloc(sizeof(struct Node));

代替Node *temp = (Node*) malloc(sizeof(struct Node));

<小时/>

如果您尝试将新元素添加到链接列表的开头,您可以将 insert() 函数更改为类似的内容

void insert(int x) {
    struct Node *temp = malloc(sizeof(struct Node));
    temp->data = x;
    temp->next = NULL;
    if(head!=NULL)
    {
      temp->next = head;
    }
    head = temp;
}
<小时/>

通过这些更改,我得到了以下输出:

How many numbers?
4
Enter the number 
12
List is:  12
Enter the number 
34
List is:  34 12
Enter the number 
56
List is:  56 34 12
Enter the number 
778
List is:  778 56 34 12

关于收集2 : fatal error:/usr/local/bin/gnm returned 1 exit status,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53844292/

相关文章:

c++ - 使用for循环在链表中添加数据

c - pthread_cancel 总是崩溃

c - 浮点类型的限制?

c++ - DWORD 在 LPVOID 上的类型转换返回什么?

c - 使用指向 const 的指针

Python;链表和遍历!

c - c中链表期间的段错误

c - gcc 不再允许空数组吗?

c - 自动发现 C 依赖项

c - 是什么导致了这个段错误?