2

I am trying to move some code from a separate binary and have it inside my main program. Unfortunately I can't mimic the initialization variables for the main function.

How can I create argc and argv by hand? Can someone give me some example assignments.

since it looks like this:

int main(int argc, char *argv[])

I figured I could assign them like this:

int argc=1;
char *argv[0]="Example";

But it doesn't work. Can anyone tell me how this might be done?

phuclv
  • 37,963
  • 15
  • 156
  • 475
napierzaza
  • 439
  • 5
  • 21
  • 2
    What you say should work. Can you post some code of what are you actually doing? – pajton Mar 29 '10 at 17:12
  • 2
    Can you provide a more complete code example? How did you "move" the function? – Felix Kling Mar 29 '10 at 17:12
  • 4
    you need to allocate space for your argv-array, one pointer worth of space, so that should be `char *argv[1] = {"Example"};` – falstro Mar 29 '10 at 17:14
  • 1
    @roe: That's mostly correct, but to be *completely* correct, he really needs `argv[argc]` to be a null pointer, so it ought to be `char *argv [2] = { "Example", NULL };` – Dan Moulding Mar 29 '10 at 17:39
  • The arguments should also be modifiable but string literals aren't. – Tronic Mar 29 '10 at 18:02
  • @Dan: why is that though? argc tells you how many entries there are – falstro Mar 29 '10 at 19:10
  • @roe: Yes, it's redundant, but the C standard says that `argv[argc]` must be a null pointer. It's best to supply it, even though it's redundant, because a conforming `main` function might expect to find it. – Dan Moulding Mar 29 '10 at 19:45

2 Answers2

6
int argc = 3;
char *argv[4];
argv[0] = "fake /path/to/my/program";
argv[1] = "fake arg 1";
argv[2] = "fake arg 2";
argv[3] = NULL;
fakemain(argc, argv);
Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • 1
    .. or just `char *argv[4] = {"fake /path/to/my/program", "fake arg 1", "fake arg 2", NULL}` to save you some real estate. – falstro Mar 29 '10 at 20:23
1

The last element of the argv[] array is actually argv[argc] which is a NULL pointer.

Some example code:

char *argv[] = { "first", "second", NULL }; 
int argc = sizeof(argv) / sizeof(*argv) - 1;
mkj
  • 2,761
  • 5
  • 24
  • 28