首页 > 解决方案 > 使用命令行参数的结构链表

问题描述

我已经编写了 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;
}

我得到分段错误或有时没有结果

标签: clinked-listsegmentation-faultcommand-line-argumentssingly-linked-list

解决方案


在访问它们之前,您必须检查是否有足够的参数。例如,如果你想“插入”

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);  
        }
}

推荐阅读