Hi guys

I use the following code to check if a user has specified a certain argument:

if (strcmp(argv[i], "-i") == 0) 
{
	// do something
}

I use the following code to check whether any arguments have been specified (e.g. -i test1) but it gives me a segemtation fault if no arg for -i is specified:

if (strcmp(argv[i], "-i") == 0) 
{
	if(strcmp(argv[i+1], "") == 0) {
		//print error
	}
}

I suspect its the "i+1" bit, as its looking for something thats not there. Can someone please tell me how to fix this.

I don't routinely use the command line so this response may be in error, but I don't think so. argc gives the number of arguments passed on the command line and argv the array of strings representing the arguments. So if argc is one the only argument passed is the program itself. If argc is more than that, then something else was passed in.

As Lerner said. Check argc first, going further than argv[argc-1] will cause a segmentation fault.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.