Question:
C programming: I can't get strcmp to work. I keep getting a segmentation fault. What am I doing wrong?
Mad Dog Laurie
2008-09-15 23:09:12 UTC
I'm running the program with no value passed to argv[1] so it should be "".

My code looks like this:

if(strcmp(argv[1], "") == 0) printf("Hi");

It compiles and runs properly if I supply an argument for argv[1] but if I run it without setting argv[1], I get a segmentation fault.

What's going on? Should the "" be NULL or something?

Can someone help please?
Three answers:
2008-09-15 23:16:07 UTC
If you don't supply an argument, there is no argv[1] so you're addressing something off in la-la land.



argc will tell you how many addressable parameters are in argv.



if (argc >=2 ) { if(strcmp(argv[1], "") == 0) printf("Hi"); }
MooseBoys
2008-09-16 06:15:24 UTC
If you don't supply an argument, a call to argv[1] segfaults because it doesn't exist (argv[1] does NOT contain the string "\0"). Use argc to check to see if argv[1] is valid first.
Michael F
2008-09-16 06:53:06 UTC
Div is exactly right. That's how you parse the command line and the 0th term is the name of the executable itself.



Have you ever wondered how printf or scanf works? You have a function call with one string argument (the format string) followed by an unspecified number of parameters. You can create these kinds of functions yourself in C. Look for va_list for explanations of how to use.



Parsing an unspecified number of command line arguments is the same process.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...