srai
srai

Reputation: 1031

copying elements of argv into a new array

I am trying to make a new copy of argv and and then pass it to the python PySys_SetArgv where i get an error :

My argv arguments are :

./matrix -r 2 -c 2 -MIN 0 -MID 10 -UPPER 50 -MAX 100

I want to make a new copy of argv called argv_new which contains arguments starting from -MIN and ending at 100. I accomplish this as follows :

char argv_new[argc-4][6];
strcpy(argv_new[0],argv[0]);
cout << argv_new[0] << "\n";    
for(int j=5; j<argc; j++)
{
    strcpy(argv_new[j-4],argv[j]);
    cout << argv_new[j-4] << "\n";

}

My output is as follows :

./matrix
-MIN
0
-MID
10
-UPPER
50
-MAX
100

Next i try to pass this argv_new into PySys_SetArgv as PySys_SetArgv(argc - 4, argv_new) to set the argv to be passed to python. However i get the following error :

cannot convert ‘char (*)[6]’ to ‘char**’ for argument ‘2’ to ‘void PySys_SetArgv(int, char**)’

I am not sure how to fix this error. Any help will be appreciated.

Upvotes: 0

Views: 604

Answers (2)

isedev
isedev

Reputation: 19631

Assuming all you want to do is skip some arguments, another solution would be to build a new array of pointers to argument strings to pass to it instead of copying the actual argument strings:

char *argv_new[argc-4];
argv_new[0] = argv[0];
for(int j=5; j<argc; j++)
    argv_new[j-4] = argv[j];
PySys_Argv(argc-4, argv_new);

Upvotes: 0

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9904

An array of pointers (as argv is) and a two dimensional array is not the same. In the first case argv[0], argv[1] etc. are real pointers that can point to completely different addresses, in the second case it's one continuous block of memory where the indexes are just read as offsets to the start address. Thus it's not possible to successfully cast one into the other.

To copy argv wou must do that:

char *argv_new[argc-4];
argv_new[0] = strdup(argv[0]);

for(int j=5; j<argc; j++)
{
    argv_new[j-4] = strdup(argv[j]);
}

(you can replace strdup(s) by malloc(strlen(s)+1) + strcpy() if you prefer that)

Upvotes: 1

Related Questions