Search code examples
c++linuxcommand-line-argumentsgetopts

Getting size of command line arguments/accessing individual characters in command line arguments


Thank you in advance for reading this,

I'm practicing getting and manipulating arguments from the command line by writing a program that takes in one argument and returns its size. From what I've read, each command line argument is null terminated and each individual character can be accessed like a normal 2D array (please correct me if I'm wrong). So I wrote:

for (int i = 0; i > -1; i++)
{
    cout << "Doing " << &argv[1][i] << endl;
    if (&argv[1][i] != "\0") Size++;
    else break;
}

This compiles fine under g++, but when I run it, this happens:

user@computer:~/Programming$ ./ReturnSize 12345
Doing 12345
Doing 2345
Doing 345
Doing 45
Doing 5
Doing 
Doing ORBIT_SOCKETDIR=/tmp/orbit-user

And then it carries on going until it segfaults. What am I doing wrong? Is there a better way of determining the size of arguments/accessing individual elements in the arguments?


Solution

  • In this statement

    if (&argv[1][i] != "\0") Size++;
    

    you compare two pointers (the string literal is implicitly converted to a pointer to its first element in this expression) . As they occupy different regions of memory the condition in the if statement will be always equal to true unless the arrays will overlap each other.

    Change this statement to

    if ( argv[1][i] != '\0' ) Size++;
    

    To get the size of a command line argument you could use standard C function std::strlen declared in header <cstring>

    For example

    size_t Size = std::strlen( argv[1] );
    

    As for your loop then it could be written simpler

    size_t Size = 0;
    while( argv[1][Size] )
    {
        cout << "Doing " << &argv[1][Size] << endl;
        ++Size;
    }