【发布时间】:2019-11-30 16:20:56
【问题描述】:
我已经编写了 C 代码来使用链表存储和使用员工数据。
逻辑完美。当我使用函数调用(注释部分)传递输入时,我得到了正确的输出。但我想尝试使用命令行参数。我不知道该怎么做,我得到了分段错误。有人可以帮我学习如何做或指出'main()'函数是否有任何错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct employee
{
char name[20];
int age;
}info;
struct node
{
info data;
struct node* next;
};
struct node* head;
void insert(char name[20], int age)
{
struct node* temp= NULL;
temp=(struct node*)malloc(sizeof(struct node));
strcpy(temp->data.name,name);
temp->data.age=age;
if(head==NULL)
{
head=temp;
head->next=NULL;
return;
}
struct node* temp1 = head;
if((temp->data.age) <= (temp1->data.age))
{
temp->next=temp1;
head=temp;
return;
}
else
{
while( (temp->data.age)>(temp1->data.age) && (temp1->next != NULL) )
{
if((temp->data.age) < (temp1->next->data.age))
{
break;
}
temp1 = temp1->next;
}
temp->next = temp1->next;
temp1->next = temp;
}
}
void print(int n)
{
if((head==NULL)||(n<1))
return;
struct node* temp = head;
if(n==1)
{
printf("%s %d\n", temp->data.name, temp->data.age);
return;
}
for(int i=1; i<=n-1; i++)
{
temp = temp->next;
if(temp==NULL)
{
printf("Specified number exceeds linked list limit\n");
return;
}
}
printf("%s %d\n", temp->data.name, temp->data.age);
}
void remove_(int n)
{
if((head==NULL)||(n<1))
return;
struct node* temp = head;
if(n==1)
{
head = temp->next;
free(temp);
return;
}
for(int i=1; i<=n-2; i++)
{
temp = temp->next;
if((temp->next)==NULL)
return;
}
struct node* temp1=NULL;
temp1 = temp->next;
temp->next = temp1->next;
free(temp1);
}
int main(int argc, char* argv[])
{
head= NULL;
if(!(strcmp(argv[1],"insert")))
{
int age=atoi(argv[3]); // ./main insert sunil 40
insert(argv[2], age);
}
if(!(strcmp(argv[1],"print"))) // ,.main print 2
{
int n=atoi(argv[2]);
print(n);
}
// insert("williamson",40);
// insert("micheal",30);
// print(5);
// print(2);
// print(1);
// insert("John",24);
// remove_(3);
// print(3);
// print(1);
// print(2);
return 0;
}
我得到分段错误或有时没有结果
【问题讨论】:
-
代码似乎运行良好,没有段错误?你能用 GDB 之类的东西包含一个堆栈跟踪吗?
-
@gunsofboom 注释行未注释时是否会出现分段错误?
-
@VladfromMoscow 当注释行未注释时,该程序运行良好,没有任何错误。只是不知道如何使用命令行参数方法传递输入
-
@gunsofboom 正如我在回答中指出的那样,函数插入无效并且具有未定义的行为。
标签: c linked-list segmentation-fault command-line-arguments singly-linked-list