Is it safe to use the argv
pointer globally? Or is there a circumstance where it may become invalid?
i.e: Is this code safe?
char **largs; void function_1() { printf("Argument 1: %s\r\n",largs[1]); } int main(int argc,char **argv) { largs = argv; function_1(); return 1; }
Once argv has been passed into the main method, you can treat it like any other C array - change it in place as you like, just be aware of what you're doing with it.
PHP Command Line Interface (CLI) Argument Handling Note that $argc and $argv are global variables, not superglobal variables.
The first element of the array, argv[0] , is a pointer to the character array that contains the program name or invocation name of the program that is being run from the command line. argv[1] indicates the first argument passed to the program, argv[2] the second argument, and so on.
Here, argc (argument count) stores the number of the arguments passed to the main function and argv (argument vector) stores the array of the one-dimensional array of strings. So, the passed arguments will get stored in the array argv and the number of arguments will get stored in the argc .
Yes, it is safe to use argv
globally; you can use it as you would use any char**
in your program. The C99 standard even specifies this:
The parameters
argc
andargv
and the strings pointed to by theargv
array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.
The C++ standard does not have a similar paragraph, but the same is implicit with no rule to the contrary.
Note that C++ and C are different languages and you should just choose one to ask your question about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With