Search code examples
cparametersargvargc

Why we use argc -1?


This is a function to reverse a given arguments , why we used argc - 1 in this context,as long as there's not null to compare in int type, is it to subtract file name from count ? and if you could show other use of argc - 1 that would be great.

int     main(int argc, char **argv)
{
    int i;

    i = argc - 1;
    while (i > 0)
    {
        printf("%s", argv[i]);
        putchar('\n');
        i--;
    }
    return (0);
}

Solution

  • I read the previous answers and I notice that they try to give you another way to re-write your code instead I'm going to explain to you how argc and argv works.

    as you may notice why we declare the argument in the main function we do this :

    int main(int argc, char **argv
    

    this means that when you try to launch the executable program you should give it some addition arguments.

    1. argc is the number of arguments being passed into your program from the command line
    2. argv is the array of arguments.

    and you should know that the array starts from 0 this means that if you want to print the last arguments in the array you can do this:

    printf("%s\n", argv[argc - 1]);
    

    for example:

    I have a program that takes a list of arguments and prints one by one and every argument followed by newline \n.

    the code:

    #include <unistd.h>
    
    int main(int argc, char **argv)
    {
        int i;
        int j;
    
        while (argv[i])
        {
            j = 0;
            while (argv[i][j])
            {
                write(1, &argv[i][j], 1);
                j++;
            }
            write(1, "\n", 1);
            i++;
        }
    }
    

    NOTE: this program doesn't use any built-in function (except wite).

    if you try to compile this code and execute it:

    ➜  Desktop gcc test.c 
    ➜  Desktop ./a.out test test1 test2
    ./a.out
    test
    test1
    test2
    ➜  Desktop