Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize argv array in C

Tags:

c

I am trying to initialize *argv with these values : test_file model result Can anyone help me how to directly initialize the argv instead of using command line. I am doing it like this:

*argv[]= {"test_file","model","output",NULL};

but its not working. I know its simple but i am new to programming. Can anyone help me?

like image 540
BlueBee Avatar asked Dec 16 '22 20:12

BlueBee


1 Answers

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 argv strings are permitted to be modified. These replacement ones cannot be (they're literals). If you need that capability (which many option parsers might), you'll need something a 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 gets called like so:

argc = new_argv( &argv, dummy_args);
like image 111
Michael Burr Avatar answered Jan 02 '23 22:01

Michael Burr