-1

I have an array of strings containing the input parameters for execvp. How can I turn it into an array of string pointers for execvp?

For command with one argument, two strings are present:

char param[4][10] = ["wc","file.txt"]

And with two arguments:

char param[4][10] = ["cp","file1.txt","file2.txt"]

If I know the number of arguments in advance, I can simply write

char *arg[]={param[0],param[1],NULL} 
execvp(arg[0],arg);

or

char *arg[]={param[0],param[1], param[2], NULL} 
execvp(arg[0],arg);

respectively.

But what can I do when I don’t know the number of arguments?

I tried looping

int count =4;
char* arg[count];
for(int i=0;i<count;i++)
{
    strcpy(exe[i],param[i]);
    printf("%s\n",exe[i]);
}
strcpy(exe[count],'\0');

but that gave me segfaults.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Safwan Ull Karim
  • 652
  • 5
  • 10
  • 20

1 Answers1

3

The arg list to execvp() needs to be the length of your param list plus one (null terminator). So if param is an array of C strings of length N:

char** arg = malloc((N + 1) * sizeof(char*));
if (arg == NULL) {
    abort();
}
for (size_t ii = 0; ii < N; ++ii) {
    arg[ii] = param[ii];
}
arg[N] = NULL;

Now you can call:

execvp(arg[0], arg);
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Thanks @John Zwinck for the quick reply. I ran into another problem though. The code char** arg = malloc((N + 1) * sizeof(char*)); shows invalid conversion from ‘void*’ to ‘char**’. This is probably because I am using g++. How can I make it run with g++, any idea? – Safwan Ull Karim Apr 26 '16 at 10:43
  • @SafwanUllKarim: add `(char**)` in front of `malloc()` to compile as C++. – John Zwinck Apr 26 '16 at 12:21
  • If you're using C++, you probably want to use `new char*[N+1]` instead of `malloc()`. – Toby Speight Apr 26 '16 at 14:24
  • @TobySpeight: The OP tagged the question as C. As for why they are compiling with g++, I'm not going to go there. – John Zwinck Apr 26 '16 at 16:05
  • @John - You're absolutely right to answer a [tag:c] question in C! – Toby Speight Apr 26 '16 at 16:12