How to access argv[] from outside the main() function?
Asked Answered
M

3

10

I happen to have several functions which access different arguments of the program through the argv[] array. Right now, those functions are nested inside the main() function because of a language extension the compiler provides to allow such structures.

I would like to get rid of the nested functions so that interoperability is possible without depending on a language extension.

First of all I thought of an array pointer which I would point to argv[] once the program starts, this variable would be outside of the main() function and declared before the functions so that it could be used by them.

So I declared such a pointer as follows:

char *(*name)[];

Which should be a pointer to an array of pointers to characters. However, when I try to point it to argv[] I get a warning on an assignment from an incompatible pointer type:

name = &argv;

What could be the problem? Do you think of another way to access the argv[] array from outside the main() function?

Miler answered 30/10, 2010 at 8:53 Comment(0)
O
8
char ** name;
...
name = argv;

will do the trick :)

you see char *(*name) [] is a pointer to array of pointers to char. Whereas your function argument argv has type pointer to pointer to char, and therefore &argv has type pointer to pointer to pointer to char. Why? Because when you declare a function to take an array it is the same for the compiler as a function taking a pointer. That is,

void f(char* a[]);
void f(char** a);
void f(char* a[4]);

are absolutely identical equivalent declarations. Not that an array is a pointer, but as a function argument it is

HTH

Omniscience answered 30/10, 2010 at 9:0 Comment(4)
+1 for being the first answer and the only answer so far explaining the mistake.Dearing
Thank you for the explanation! I was using argv as char *argv[] so I thought of an array pointer in the beginning.Miler
@Johannes, @Sergi: Thanks, I wish C/C++ books put a bigger accent about differences of arrays and pointers. These get way too often mixed up...Omniscience
Be careful with this - the content may be modified after name is assigned (I believe this does happen, with some argument-handling functions such as in Qt). To be robust, the application really ought to make a deep copy of the arguments.Easygoing
P
5

This should work,

char **global_argv;


int f(){
 printf("%s\n", global_argv[0]); 
}

int main(int argc, char *argv[]){
  global_argv = argv;
 f(); 
}
Picard answered 30/10, 2010 at 9:1 Comment(0)
S
-1
#include <stdio.h>

int foo(int pArgc, char **pArgv);

int foo(int pArgc, char **pArgv) {
    int argIdx;

    /* do stuff with pArgv[] elements, e.g. */      
    for (argIdx = 0; argIdx < pArgc; argIdx++)
        fprintf(stderr, "%s\n", pArgv[argIdx]);

    return 0;
}

int main(int argc, char **argv) {
    foo(argc, argv);
}
Splenetic answered 30/10, 2010 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.