0

Problem

I've this simple script to verify the argv. The problem is that if I try to input the argv 1 to "-help" it don't print the string "banner". Why it is not printing the string?

I think that is important to say that I'm noobie with the C language.

Script

#include <stdio.h>
#include <conio.h>

void main(int argc, char *argv[ ]){
    int cont;

    printf("argv 1 -> %s", argv[1]);

    if(argv[1] == "-help"){
        printf("banner");
    }

    if(("%s", argv[1]) == "-help"){
        printf("banner");
    }

//main
}
Black Coral
  • 55
  • 2
  • 6

1 Answers1

1

argv[1] == "-help" is comparing pointers, not the contents of strings. It will never be true because it is comparing variable region and fixed region.

("%s", argv[1]) == "-help" has the same meaning with argv[1] == "-help". , here is a comma operator.

You should use strcmp() to compare strings in C. Also don't forget to check if argv[1] has meaningful value.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[ ]){

    if (argc >= 2) {
        printf("argv 1 -> %s", argv[1]);

        if(strcmp(argv[1], "-help") == 0){
            printf("banner");
        }
    }

//main
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70