Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize/set char *argv[] inside main() in one line

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:

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

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

like image 212
herohuyongtao Avatar asked Dec 06 '22 04:12

herohuyongtao


2 Answers

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
like image 183
Emilio Garavaglia Avatar answered Dec 26 '22 10:12

Emilio Garavaglia


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]);
    }
}
like image 26
xaizek Avatar answered Dec 26 '22 10:12

xaizek