1

$ ./Main a

int main(int argc, char * argv[]) {
int i;
for(i=1;i<argc;i++){
    if(argv[i] == NULL){ //This line does not work!
        argv[i] = "Null";
    }
}
theMenu(argv[1], argv[2], argv[3], argv[4]);
return (EXIT_SUCCESS);}

In theMenu function,when I called strcmp(argv[2],argv[3]); I will have segmentation fault :((

How can I make argv[x] = "Null" when user did not enter the parameter at x?

4 Answers 4

4

The CRT will not insert NULL entries for arguments you didn't receive. It will simply reduce the value of argc instead. If you must have four arguments, then you can define your own array on the stack.

int main(int argc, char * argv[]) {
    char* args[4] = { 0 };
    int i;
    for(i=1;i<argc && i < 4;i++){
         args[i] = argv[i];
    }
    for(int i = 0; i < 4; i++) {
        if (args[i] == NULL)
            args[i] = "Null";
    }
    theMenu(argv[1], argv[2], argv[3], argv[4]);
    return (EXIT_SUCCESS);
}
Sign up to request clarification or add additional context in comments.

1 Comment

"The CRT will not insert NULL entries for arguments you didn't receive": however, notice that the after the last valid element of argv there's always one element containing NULL, i.e. argv[argc]==NULL. (this obviously is just nitpicking, I actually upvoted you)
2

You can't. What you can do is define your own array of size [4] initialized to empty strings or NULLs and copy arguments (up to argc count) there.

Comments

1

Your problem is that argc<5 and so you are attempting to access elements of argv that are not defined.

Comments

1

You're expecting 4 arguments. Why not trap it like so:

if (argc==5)
{
//code here
}

(it is 5 because there is an arg[0] when you run your code)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.