Home > Blockchain >  If argc is 1, can I still use argv[1], argv[2],... character arrays?
If argc is 1, can I still use argv[1], argv[2],... character arrays?

Time:09-26

If there is no argument passed from the command line ie. if argc is 1, can we still allocate memory for argv[1],argv[2],..... and use those buffers for further experiments. If that is undefined behavior, can I still use it somehow?

CodePudding user response:

No, the C standard does not specify that argv has any elements beyond argv[argc], so they may not exist in C’s object-memory model and the behavior of using them is not defined by the C standard.

C 2018 5.1.2.2.1 2 says:

argv[argc] shall be a null pointer.

If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup.

That is all there is that defines the extent of the argv array; nothing in the standard says there are more elements.

When argc is one, using argv[1] is defined but using argv[2] is not.

You can store new values to the defined elements because C 2018 5.1.2.2.1 2 also says:

The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

CodePudding user response:

can I access argv[] elements after argv[argc]?

You can ... but ONLY IN THIS CODE

#include <stdio.h>

int main(int argc, char **argv) {
    if (argc == 1) {
        char *foo[] = {"bar", "baz", "quux", NULL, "bingo"};
        main(3, foo);
    } else {
        printf("argc is %d; argv[4] is \"%s\"\n", argc, argv[4]);
    }
    return 0;
}

See code running on ideone.

In all other codes, you cannot.

CodePudding user response:

Always argv[argc] is equal to NULL. In the described case where argc is equal to 1 the array argv contains two pointers argv[0] and argv[1] where argv[1] is a null pointer.

You may reassign the pointers but this does not make a great sense because that will make your program unclear. Instead you could declare your own array if you need.

  • Related