Can't compare argv?
Asked Answered
J

7

5

I have this code:

if (argv[i] == "-n") 
{
    wait = atoi(argv[i + 1]);
}
else 
{
    printf("bad argument '%s'\n",argv[i]);
    exit(0);
}

When this code gets executed I get the following error:

bad argument '-n'

I seriously don't know why it does that. Can someone explain?

Jeanne answered 21/11, 2010 at 17:52 Comment(0)
W
15

String comparisons need a function in C - usually strcmp() from <string.h>.

if (strcmp(argv[i], "-n") == 0) 
{
    wait = atoi(argv[i + 1]);
}
else 
{
    printf("bad argument '%s'\n",argv[i]);
    exit(0);
}

The strcmp() function returns a negative value (not necessarily -1) if the first argument sorts before the second; a positive value (not necessarily +1) if the first arguments sorts after the second; and zero if the two values are equal.

Wheelwork answered 21/11, 2010 at 17:54 Comment(0)
A
1

The == operator does not work on the contents of strings because strings are effectively character pointers in this application, and the pointer get compared.

To compare the contents of strings use strcmp or strncmp.

Assort answered 21/11, 2010 at 17:55 Comment(0)
S
0

You are comparing pointers (argv[i] and of "-n" are a char* and a const char*).

Use strcmp() instead.

Spiritoso answered 21/11, 2010 at 17:55 Comment(0)
R
0

What you're really doing here is pointer comparison. argv[i] is not a string, it's a pointer to a location in memory at which the actual string starts. Use strcmp().

Roadbed answered 21/11, 2010 at 17:55 Comment(0)
P
0

You're comparing pointers, not string contents. argv[i] and "-n" are two different strings, stored at two different locations in memory, even if the characters inside the strings are equal.

Peseta answered 21/11, 2010 at 17:56 Comment(0)
B
0

In C, the operator == compares for equality.

Values of the same numeric type are compared the straightforward way (i.e. 2 + 2 == 4 is true).

Values of different integer (and non-integer numeric) types undergo some conversion. See elsewhere.

Pointers are equal if the point at the same address.

String literals are placed in memory not overlapping any other thing; including not overlapping anything pointed to by argv[i] (for i = 0 to argc).

So you're comparing two unequal pointers; that's why. You want to use if (!strcmp(argv[i], "-n")) { ... }.

Boling answered 21/11, 2010 at 17:57 Comment(0)
R
0
int equal(char* stringa, char* stringb) {
    while((*stringa) && (*stringb)) {
        if(*stringa!=*stringb)
            return FALSE;
        stringa++;
        stringb++;
    }
    return TRUE;
}

is also working for me

Rainband answered 5/10, 2015 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.