Question

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?

Was it helpful?

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;
}

OTHER TIPS

for (int i = 0; i > -1; i++) really ??? A simple way ::

#include<iostream>
#include<cstdlib>
int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; ++i)
    {
        std::string temp = argv[i];
        std::cout << temp << " | " << temp.length() << std::endl;
        Size = temp.length();
    } 
    return 0;
}

Apart from the fact that the whole program's a bit odd (see pippin1289's comment), your if condition is wrong: you want:

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

The for loop makes no sense. You increment i and test whether it is greater than -1. Of course it is. Testing against string "\0" isn't the same as testing against the null character '\0'. That is one of the sources of your trouble. Also I wouldn't bother looping character by character in the first place. You can just send the whole string to the stream, or use the C library functions on it.

Any boolean expression may be evaluated. For example, you can write:

for (int i = 0; true; i++) {
}

That being said, something like

for (int i = 0; i argv[1][i] != '\0'; i++) {

}

may work although unconventional

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top