Frage

I've got the main function: main(int argc, char *argv[]). I want to use these variables: argc,argv in other function:

int function()

int main(int argc, char *argv[])
{
 ...
 function();
 ...
 return 0;
}

int function()
 {
 int b=argc;
 return 0;
 }

but the compilator give error, that argv is undeclared. How can I use these variables in other functions?

War es hilfreich?

Lösung 3

argc and argv are local variables of main. You can pass them to other functions as arguments. For example

int function( int );

int main(int argc, char *argv[])
{
 ...
 function( argc );

Andere Tipps

Pass them as arguments to your functions.

int function(int argc)
{
   int b = argc;
   return 0;
}

and call

function(argc);

in main

As you tagged this as C++ too, you can do the following trick:

int argc;
char **argv;

void foo() {
    printf("argc: %d\n", argc);
    for (int i=0; i < argc; i++)
        printf("%s \n", argv[i]);
}

int main(int argc, char **argv)
{
    ::argc = argc;
    ::argv = argv;
    foo();
    return 0;
}

declare function as

int function (int argc) {
    int b = argc;
    ....
}

call function in main like

function(argc);

OR

use a static variable to store your argc and argv, but this is not recommanded

before you main

int g_argc;
char* g_argv[];

in your main function

g_argc = argc;
g_argv = argv;
function();

int your function just use g_argc directly

Another alternative would be to make two global variables to hold the same values as argc and *argv

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top