[ACCEPTED]-How to initialize argv array in C-c

Accepted answer
Score: 12
char* dummy_args[] = { "dummyname", "arg1", "arg2 with spaces", "arg3", NULL };

int main( int argc, char** argv)
{
    argv = dummy_args;
    argc = sizeof(dummy_args)/sizeof(dummy_args[0]) - 1;

    // etc...

    return 0;
}

One thing to be aware of is that the standard 6 argv strings are permitted to be modified. These 5 replacement ones cannot be (they're literals). If 4 you need that capability (which many option 3 parsers might), you'll need something a 2 bit smarter. Maybe something like:

int new_argv( char*** pargv, char** new_args) 
{
    int i = 0;
    int new_argc = 0;
    char** tmp = new_args;

    while (*tmp) {
        ++new_argc;
        ++tmp;
    }

    tmp = malloc( sizeof(char*) * (new_argc + 1));
    // if (!tmp) error_fail();

    for (i = 0; i < new_argc; ++i) {
        tmp[i] = strdup(new_args[i]);
    }
    tmp[i] = NULL;

    *pargv = tmp;

    return new_argc;
}      

That 1 gets called like so:

argc = new_argv( &argv, dummy_args);
Score: 1

or simply put, does this work (sorry its 1 3 years late ;) ) ?

int argc ;
char * argv[3] ;

char  p1[16]  ;
char  p2[16]  ;
char  p3[16]  ;

memcpy ( p1, "mainwindow", 9 ) ;
memcpy ( p2, "–SizeHint5", 10 ) ;
memcpy ( p3, "120x240", 7 )  ;

argc = 3 ;
argv[0] = p1 ;
argv[1] = p2 ;
argv[2] = p3 ;

QApplication app(argc, argv);
Score: 0

Initialisation like that is only available 4 at declaration time, and (presumably) you've 3 declared argv as a parameter to your function 2 (main I assume). You will have to assign each 1 individually in this instance.

Score: 0

To conform with newer compilers, I would 2 do this (as long as you don't want to change 1 the strings):

char* argv[] = {const_cast<char*> ("program_name"),
                const_cast<char*> ("-arg1"),
                const_cast<char*> ("string_to_arg1"),
                const_cast<char*> ("-arg2"),
                const_cast<char*>("-arg3"),
                NULL};
int argc = sizeof (argv) / sizeof (char*) - 1;

QApplication app(argc, argv);

More Related questions