首页 > 解决方案 > collect2:致命错误:/usr/local/bin/gnm 返回 1 个退出状态

问题描述

我写了一个链表作为

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 提供了一些有用的提示。

我的代码有什么问题?

标签: cpointerslinked-list

解决方案


当您有一个指向结构的指针时,例如temp在您的insert(), 而不是做类似的事情

(*temp).data

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

temp->data

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

struct Node var_name;

代替

Node var_name;

在 C 中,最好不要显式转换malloc(). 看到这个

因此将tempin的声明更改insert()

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

推荐阅读