Questions about argv

Asked 2 years ago, Updated 2 years ago, 32 views

The program uses a linked list to store it in memory, and at the end of the program, argv[0] stores the path as data.dat, and I understand that less options are stored when it starts at argv[1. However, you can see that it was actually given argc = 3 at the time of execution, and you have to use argv[2] within the code. So I wonder how argc = 3 was determined in this code. And I wonder what argv[1] stores.

 //linked_list.h
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
struct Linked_list
{
    char Name[10];
    struct Linked_list *next;
};

typedef struct Linked_list Node;

int size;
#endif

//main.c
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"

#define FNUM 2

void registerNode();
void print();
void (*pFuncs[FNUM])()={registerNode, print};


Node* head;

int main(int argc, int** argv)
{
    int size = 0;
    int select = 0;
    Node* target = malloc(sizeof(Node));
    FILE *fp = fopen(argv[2],"wb");

    head = malloc(sizeof(Node));
    head->next = NULL;

    while(select != 3)
    {
        printf("1.Register\t 2.Print\t 3.Exit\nSelect number : ");
        scanf("%d", &select);
        if(select>0 && select<=FNUM)
            pFuncs[select-1]();
        else if(select != 3)
            printf("You choose wrong number\n");
    }

    while(target != NULL)
    {
        fwrite(target,sizeof(Node),1,fp);
        target = target->next;
    }

    fclose(fp);

    return 0;
}

void registerNode()
{
    Node* current = head;
    Node* tmp = malloc(sizeof(Node));

    for(int i = 0; i < size; i++)
    {
        current = current->next;
    }

    while(getchar()!='\n');//buffer empty
    printf("Name : ");
    gets(tmp->Name);
    printf("\n");

    current->next = tmp;
    tmp->next = NULL;
    size++;

    return; 
}

void print()
{
    Node *target_Node = head->next;

    while(target_Node != NULL)
        {
        printf("Name : %s\n", target_Node->Name);
                target_Node = target_Node->next;
        }

    printf("\n");

    return;
}

c linux

2022-09-21 20:00

1 Answers

argv's content is all options

Looking at the debug screen, you can say that it was executed like this.

/testing/main ./main data.dat
------------- ------ --------
   argv[0]    argv[1] argv[2]


2022-09-21 20:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.