The parameter argv
is a array of arrays of chars. When you use argv[1]
, what you’re actually accessing is a pointer to the start of array of chars which represents the second argument passed to the program.
On the line argv[1] == 'b'
, as argv[1]
and 'b'
are of different types the compiler makes a cast implicit variables. In this case what is compared is value of argv[1]
, a memory address, with 98
, which is the ASCII value of the character 'b'
, as the two are always different the comparison fails.
Also know that although the following Compile code, it may not produce what you expect.
char str1[] = "abc";
char str2[] = "abc";
if (str1 == str2) {
printf("iguais");
} else {
printf("diferentes");
}
When you only access the name of array what you receive is the pointer to the first element of it, so what is compared are the memory addresses, not the contents of the strings.
For you to compare strings, which in C are only arrays of chars ended in NULL
, you need to use the function strcmp
header string.h
This function receives two strings and returns:
- < 0 if
str1
is less than str2
- > 0 if
str1
is greater than str2
- 0 if
str1
and str2
are the same
Your corrected code would look like this:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv []){
if (argc < 2) return 0;
if (strcmp(argv[1], "b") == 0){
printf("Bom dia");
}
}
Note that you should always check whether the correct number of arguments were passed to the program before accessing some value from argv
, otherwise your program may access memory junk, which may produce unexpected results.
if (*argv[1] == 'b'){
– TigerTV.ru