Search code examples
c++charargv

Why is argv[1] an entire word and not a single letter?


I'm learning c++ and one thing I can't seem to find a good explanation of is how char* argv[] works. I understand that it is an array of characters, but from what I understand if you had

char myword[] = "Hello";

then myword[1] is "e".

So when using argv[], why is argv[1] the entire first argument and not just the second letter of the program name? There is something here I don't understand but I'm not sure what....

Thanks for any explanations!


Solution

  • You seem to miss the point that argv (as in int main(int argc, char* argv[])) is a pointer to pointer to char, not the char.

    Some funny stuff about arrays and pointers. Since a pointer can be treated to an array (provided it points to an array) and arrays can be treated as pointers (technical term for this is decay to pointers) an array and pointer can be often used interhargeably.

    However, when doing so, one still needs to keep in mind that at certain times, there is a stark difference between array and pointer. One of the most visible (not the only one!) is the difference in their sizes.

    For example:

    char argv[] = "Test!";
    char* pargv = argv;
    
    size_t s_argv = sizeof(argv); // equals to 6 - 5 letters of Test! + \0
    size_t s_pargv = sizeof(pargv); // equals to whatver size of pointer you have, i.e. 4 or 8