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?

4

7 に答える 7

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.

于 2010-11-21T17:54:28.770 に答える
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.

于 2010-11-21T17:55:28.877 に答える
0

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

Use strcmp() instead.

于 2010-11-21T17:55:39.730 に答える
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().

于 2010-11-21T17:55:48.847 に答える
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.

于 2010-11-21T17:56:39.547 に答える
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")) { ... }.

于 2010-11-21T17:57:47.873 に答える
0
int equal(char* stringa, char* stringb) {
    while((*stringa) && (*stringb)) {
        if(*stringa!=*stringb)
            return FALSE;
        stringa++;
        stringb++;
    }
    return TRUE;
}

is also working for me

于 2015-10-05T14:48:14.410 に答える