Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicating an array of strings (or copying them to another array)?

I need the arguments that were passed to my process when it was started. This means, of argv[] I need all but the first (which is my process's name).

I am having trouble copying it, because of it being type char * argv[]. Can anyone give me the gist of how to do it properly, or perhaps a small code snippet. I'd prefer that to banging my head on the wall.

EDIT:

Clarifying my problem:

The key thing is I need all but the first argument of argv. So i can't just send it off to other processes, as I am actually using it as an argument to execv.

like image 667
Blackbinary Avatar asked Dec 09 '22 10:12

Blackbinary


1 Answers

There's no point copying the strings - they will persist for the lifetime of the program and you aren't allowed to modify them. Just pass argc and argv around to whoever needs them, or copy them to global variables.

#include <stdio.h>

int myargc;
char **myargv;

void print_args()
{
    int i;
    for (i = 1; i < myargc; ++i) {
        puts(myargv[i]);
    }
}    


int main(int argc, char **argv)
{
    myargc = argc;
    myargv = argv;

    print_args();

    return 0;
}    
like image 69
fizzer Avatar answered May 30 '23 17:05

fizzer