collect2: фатальная ошибка: / usr / local / bin / gnm вернул 1 состояние выхода - PullRequest
0 голосов
/ 19 декабря 2018

Я написал связанный список как

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 предоставляет несколько полезных советов.

В чем проблема с моим кодом?

1 Ответ

0 голосов
/ 19 декабря 2018

Когда у вас есть указатель на структуру, как в случае temp в вашем insert(), вместо того, чтобы делать что-то вроде

(*temp).data

, вы можете использовать оператор стрелки и сделать

temp->data

Поскольку это программа на C, при объявлении структурных переменных структуры Node необходимо использовать

struct Node var_name;

вместо

Node var_name;

А в C лучше не приводить явно возвращаемое значение malloc().См. this .

Поэтому измените объявление temp в 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...