-5
#include <unistd.h>

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

    i = 0;
    if (argc != 2)
        write(1, "a\n", 2);
    else
    {
        while (argv[1][i])  /*<<< the box [] with i */
        {
            if (argv[1][i] == 'a')  /*<<< and here */
            {
                write(1, "a", 1);
                break ;
            }
            i += 1;
        }
        write(1, "\n", 1);
    }
    return (0);
}

I'm fairly new to C programing, I need someone to explain me what the second [] box in argv do. What can it be used for, is there any specific name for the second [], and how does it work?

Vestrius
  • 5
  • 4
  • Read the chapter(s) about arrays, pointers and multidimensional arrays in [your favorite C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – bolov Jan 16 '21 at 12:01

2 Answers2

1

If you call your executable, for instance, with one of these

$ ./executable one foobar
> program.exe one foobar

You get

argc == 3

argv[0] ==> "./executable" or "program.exe"
argv[1] ==> "one"
argv[2] ==> "foobar"
argv[3] == NULL

argv[2][0] == 'f'
argv[2][1] == 'o'
argv[2][2] == 'o'
argv[2][3] == 'b'
argv[2][4] == 'a'
argv[2][5] == 'r'
argv[2][6] == 0
pmg
  • 106,608
  • 13
  • 126
  • 198
0
char *p;

in C language *(p + i) is the same as p[i].

So if have char *argv[] (array of pointers to char) then argv[i] is a char *. The second index will be equivalent to the example above.

It is easier to understand if we add add an additional variable which will remove the second double indirection.

    else
    {
        char *argument = argv[1];
        while (argument[i])  /* now it is very easy to understand */
        {
            if (argument[i] == 'a')  /*<<< and here */
            {
                write(1, "a", 1);
                break ;
            }
            i += 1;
        }
        write(1, "\n", 1);
    }

I would strongly advise using such additional variables as it is making the code easier to read and understand. The optimizing compiler will get rid of them and the code will be the same as without them.

0___________
  • 60,014
  • 4
  • 34
  • 74