4

Sorry, I'm a rookie in C. What I am trying to do is just to print something if --help parameter is entered to the terminal like ./program --help. So the code is this:

char *HELP = "--help"; char *argv1 = argv[1]; if (argv1 == HELP) { printf("argv[1] result isaa %s\n", argv[1]); } 

So even if I use --help parameter it does not pass through the if condition. So what could be the reason behind that?

1
  • Note that you will have to include different .h files anytime you call functions. So, your question below about warning: implicit declaration of function ‘strcmp’ can be answered by entering the command man strcmp which will tell you which file your function is defined in and therefore needs to be included. (If your OS is not *nix based, just google 'man strcmp' to get the same information) Commented Aug 23, 2012 at 15:32

6 Answers 6

12

That's not how you compare strings in C. Use strcmp or strncmp:

if (strcmp(argv1, HELP) == 0) 

Include string.h to get access to those.

Sign up to request clarification or add additional context in comments.

3 Comments

warning: implicit declaration of function ‘strcmp’ [-Wimplicit-function-declaration]
@SarpKaya #include <string.h>
For a beginner, it's (in my opinion) much clearer to compare against 0, instead of using the ! operator.
4

That is comparing the addresses, not the content. Use strcmp():

if (0 == strcmp(HELP, argv1)) { printf("argv[1] result isaa %s\n", argv[1]); } 

Be sure and check that argc > 1 before accessing argv[1].

Comments

3

In C, there is no string type. You've declared char *HELP, so HELP is a char *, not a string. In the if, you are comparing two pointers, instead of the string they point to. You will want to call strcmp (string compare), a function that receives two char *, and compares the strings pointed by them.

Comments

0

You shoul use strcmp.

result=strcmp(argv1,HELP); if(result==0) { --what you want } 

Comments

0

char *HELP = "--help"; - Here --help is a string literal which is a read only data in text segment. You are just assining the address to the pointer variable HELP.

`argv[1] will given you the address where the first commandline arguemet is stored.

So argv[1] and HELP are having different address. So the condition (argv[1] == HELP) is just checking the address stored in these two pointer variables. Always this will fail.

Actually you have to compare the content of these two pionters. For this you can impelement the string compare logic or use the strcmp function.

if (0 == strcmp(argv[1], HELP) { //do your stuff } 

Comments

0

I had same problem. my problem is solved by using strncmp.
strcmp doesnt work for my problem anyway

#include <string.h> if (strncmp(argv1, HELP,6) == 0) //6 is size of argument { //do smt } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.