Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use the argv pointer globally?

Tags:

c

argv

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; } 
like image 697
Steve Dell Avatar asked Jul 24 '15 07:07

Steve Dell


People also ask

Is it safe to modify argv?

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.

Is argc and argv global?

PHP Command Line Interface (CLI) Argument Handling Note that $argc and $argv are global variables, not superglobal variables.

Why do we use argv?

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.

Why do you need to use argc and argv [] in your main function and what does it do?

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 .


1 Answers

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 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.

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.

like image 154
TartanLlama Avatar answered Sep 22 '22 15:09

TartanLlama