I want to initialize/set char *argv[]
inside the main()
so that I can use argv[1], argv[2]...
later in my program.
Up to now, I know how to do this in two ways:
For int main()
, use one line as:
int main()
{
char *argv[] = {"programName", "para1", "para2", "para3", NULL};
}
Note that, using NULL
in the end is because the pointers in the argv
array point to C strings, which are by definition NULL
terminated.
For int main(int argc, char* argv[])
, I have to use multiple lines as:
int main(int argc,char* argv[])
{
argv[0] = "programName";
argv[1] = "para1";
argv[2] = "para2";
argv[3] = "para3";
}
My question is that how can I combine these two methods together, i.e. use only one line to initialize it for int main(int argc, char* argv[])
? Particularly, I want to be able to do like this (this will be wrong currently):
int main(int argc, char* argv[])
{
argv = {"programName", "para1", "para2", "para3", NULL};
}
How can I be able to do this?
Edit: I know argv[]
can be set in Debugging Command Arguments
. The reason that I want to edit them in main()
is that I don't want to bother to use Debugging Command Arguments
every time for a new test case (different argv[]
setting).
The safest way is probably don't write into argv referred memory, (that may not be structured as you think), but having another bulk:
int main(int argc, const char** argv)
{
const char* n_argv[] = { "param0", "param1", "param2" };
argv = n_argv;
...
}
This will distract argv from it original memory (owned by the caller, that remains there) to another that will exist for the life of main().
Note that const char*
is required to avoid the deprecated "*string assigned to char**" message.
NOTE: this code had been compiled with GCC 4.8.1 on Linux giving the following results:
make all
Building file: ../main.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pedantic -Wall -c -std=c++11 -o "main.o" "../main.cpp"
Finished building: ../main.cpp
Building target: e0
Invoking: GCC C++ Linker
g++ -o "e0" ./main.o
Finished building target: e0
If you're able to use C99, you can use compound literals feature. Here's an example that seems to work when compiled as gcc -std=c99 main.c
:
#include <stddef.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
argv = (char *[]){"programName", "para1", "para2", "para3", NULL};
char **p = argv;
argc = 0;
while (*p++ != NULL) {
argc++;
}
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
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