c - 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 提供了一些有用的提示。
我的代码有什么问题?
解决方案
当您有一个指向结构的指针时,例如temp
在您的insert()
, 而不是做类似的事情
(*temp).data
您可以使用箭头运算符并执行
temp->data
由于这是一个 C 程序,所以在声明结构的结构变量时Node
,必须使用
struct Node var_name;
代替
Node var_name;
在 C 中,最好不要显式转换malloc()
. 看到这个。
因此将temp
in的声明更改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
推荐阅读
- oracle - Oracle PL/SQL 如何在巴黎打发时间?
- vue.js - 如何处理 eslint-disable-next-line 与 prettier 的冲突?
- javascript - Sendgrid 动态模板从 Anchor 标记中剥离 HREF
- c# - 如何在 asp.net 核心 mvc/razor 页面混合应用程序中使默认页面使用 MVC 默认页面,“主页/索引”页面
- vue.js - 将 Nuxt 配置为按路由或页面包含 CSS,而不是全局
- c# - 如何在linq内部连接中添加小于或等于条件
- java - 如何在Android中使用Java在每个项目中生成具有不同背景颜色的微调器?
- selenium - 没有为多个套件生成范围报告
- hibernate - Hibernate Envers:阻止 onPostDelete 上的版本
- javascript - 是否可以使用 XPath 获得此结果集?