c - 使用命令行参数的结构链表
问题描述
我已经编写了 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;
}
我得到分段错误或有时没有结果
解决方案
在访问它们之前,您必须检查是否有足够的参数。例如,如果你想“插入”
int main(int argc, char* argv[])
{
head= NULL;
if(argc > 3)
if(!(strcmp(argv[1],"insert")))
{
int age=atoi(argv[3]); // ./main insert sunil 40
insert(argv[2], age);
}
}
推荐阅读
- assembly - 强制 RIP 相对寻址?
- docker - Groovy sh 调用 docker build 正在向我的命令添加换行符
- sas - SAS中的转置数据集
- python-3.x - 用于根据另一列中的字符串删除列中不需要的字符串元素的 Pandas 或 Python 方法
- reactjs - 如何在 ReactJS 中存储、提交和复制表单中的输入到另一个组件
- excel - Excel 命名范围以 C 和一个数字开头
- c++ - 从全局对象的构造函数调用 std::ofstream 时不创建文件
- c++ - C++ EGL 使用 PBuffer Surface 渲染到纹理
- javascript - D3.js 动画
- python - 如何准备字符串以使用不明确的数组进行格式化?