Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compare argv?

Tags:

c

argv

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?

like image 811
Kristina Brooks Avatar asked Nov 21 '10 17:11

Kristina Brooks


2 Answers

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.

like image 133
Jonathan Leffler Avatar answered Sep 19 '22 05:09

Jonathan Leffler


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.

like image 36
dmckee --- ex-moderator kitten Avatar answered Sep 21 '22 05:09

dmckee --- ex-moderator kitten