-3

I'm trying the following codes, but got unexpected result.

//the first element in argv[] is a
int main(int argc, char *argv[]) {
    char a;
    
    if (*argv ==  "a")
    {
        printf("a");
    }
    
}

I got nothing after excution, so that means the condition *argv++ == "a" is false. So why?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
o o
  • 145
  • 6

2 Answers2

1

In this if statement

if (*argv ==  "a")

there are compared two pointers. The first one is the pointer to the first character of the string pointed to by the pointer *argv and the second one is the pointer to the first character of the string literal "a".

As these two strings occupy different extents of memory then the comparison of the pointers always evaluates to logical false.

If you want to compare pointed strings then you need to use the standard C string function strcmp. For example

if ( strcmp( *argv, "a" ) == 0 )

If you want to compare first characters of the strings then you should write

if ( **argv ==  *"a" )

or just use the character 'a' instead of the string literal that is more natural

if ( **argv ==  'a' )

Pay attention to that if *argv is not equal to NULL then this pointer points to the string that denotes the running program.

Maybe you actually mean the following if statement

if ( argc > 1 && strcmp( argv[1], "a" ) == 0 ) 

if you want to check whether the first command line argument is equal tp the string literal "a".

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

char *argv[] is an array of pointers to char.

    // myapp.c - program to print out all command line parameters
    #include <stdio.h>

    int main (int argc, char *argv[]) {
        int i ;
        for (i = 0; i < argc; i++) {
            printf ("arg %d = %s\n", i + 1, argv[i]) ;
        }
        return 0 ;
    }

If one were to compile this code and run it at the command line like this:

myapp This That another

It would print out

arg 1 = myapp
arg 2 = This
arg 3 = That
arg 4 = another

So, let's say *argv points to 0x0800001000 (in RAM) and "a" is held at address 0x090000000 (in RAM). What you are doing is like saying:

if (0x0800001000 == 0x090000000) {
...
}

which is always going to be false (unless something really weird happens)

I'm not entirely sure what you want to do, but there are two possibilities

  1. You want to compare the first string passed in on the command line to "a"
// do it like this
if (strcmp(argv[1],"a") == 0) {
...
}
  1. You want to compare the first character of the first string passed in on the command line to 'a'
// do it like this
if (argv[1][0] == 'a') {
...
}

We use argv[1] because argv[0] is just the name of the executable

Edgen
  • 69
  • 7