Search code examples
cpointersscopeargvargs

Pass main's *argv[] to a function that is being called by another function?


So I have my main function, and 2 other functions, func1 and func2. main is gettings the arguments from the user, passes them to func1. fun1 checks something, and then wants to send the arguments to func2.

How can I do it?

 int main( int argc, char *argv[] )  {
  if( argc == 3 ){
    func1(argv);
  }

void func1(char **argv){
if(strcmp(argv[2], "-win"))
    func2(argv);
}

void func2(char ***argv){ //is this the right way?
......
}

I mean I know that func1 is receiving the arguments because when I tried it without sending them to func2, it worked. But I'm trying to figure out how to send them to func2 from func1.


Solution

  • Look at this code in file main.c:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void func1(char **argv);
    void func2(char **argv);
    
    int main(int argc, char *argv[])
    {
        // you are need to pass 2 things to run this
        if (argc == 3)
        {
            func1(argv);
        }
        return 0;
    }
    
    void func1(char **argv)
    {
        if (strcmp(argv[2], "-win")==0)
            func2(argv);
    }
    
    void func2(char **argv)
    {
        printf("%s\n", argv[2]);
    }
    

    Running gcc -Wall main.c -o main && ./main f -win you get the output: -win to the console. You shouldn't manipulate data within argv and it is a safer bet to just change func2 to:

    char *func2(char **argv)
    {
        // Return some value after receiving argv
    }
    

    and return whatever type your result is of the manipulation you are wanting to do.