Take the 2-minute tour ×

Given a command line tool which I use in the command line like this: ./tool img/file.png

How can I assign the first argument to a variable? I tried *argv[1], &argv[1], malloc(sizeof(argv[1])) but then I get an invalid initializer error. Did I just not get a basic C concept or where am I stuck? Thanks for your help!

int main(int argc, char ** argv) {

    char block1_arg_Filename[] = "img/file.png"; //that's how it works but I don't need it

    char block1_arg_Filename[] = argv[1]; // don't get it to work but that's how I need it


    return 0;

share|improve this question
what is a "C script"? –  glglgl Jun 20 '13 at 12:33
@glglgl Correct me straight forwardly, if this is the purpsose of your question :) –  Steven Jun 20 '13 at 12:42
& preferrably, don't use char ** argv. Use char *argv[]. –  anishsane Jun 20 '13 at 12:46
To the compiler, there's no difference between char ** argv and char *argv[]; though I do agree, the latter probably conveys intention somewhat better. –  Vilhelm Gray Jun 20 '13 at 12:58

3 Answers 3

up vote 1 down vote accepted
char* block1_arg_Filename = argv[1];

Of course, check argc > 1 before trying this.

share|improve this answer
Thanks for the quick reply, but still the same error... some lines down I pass it to a function where a warning is displayed too: 'passing argument 1 of cvLoadImage from incompatible pointer type. I only get the "invalid initializer" error and no warning when using const char. I would be grateful for any further ideas :) –  Steven Jun 20 '13 at 12:28
Argh... sorry, forgot to get rid of the "[]" Thank you! –  Steven Jun 20 '13 at 12:43

First you should check that the argument exist, by checking argc. Then simply assign it to a char * if you can't use argv[x] directly (which you should be able to do).

share|improve this answer
int main(int argc, char ** argv) {

    if (argc > 1) {
      char *str = argv[1];
      /** do some stuff **/

    return 0;


try this

share|improve this answer
If you try this if pattern with more than a couple arguments you gonna have a bad time. –  Benjamin Bannier Jun 20 '13 at 12:56

Your Answer


