I am making a program that can take another program as an argument and run it.
I am using execv() to run the second program, but how can I use argv[] (that comes from the main program, is a char*) as arguments for execv()?
The first element of argv[] is the name of the main program, so I need to start at the second element where the name of the next program is located.
I am thinking there might be different solutions, for example:
- Tell
execv()to start from the second argument - copy the content of
argv[](except first element) to another array and use that - Something with pointers so maybe I can point to the second element and start there
What is the best way to do this? And can I get an example of how to do it?
First of all, the
argvis actually a pointer to array of pointers. The more correct way to define it would bechar **argv.Defining it as
*argv[]is just a syntactic sugar. So your third guess is a best one:You can also play with interchanging function arguments
char **argvvschar *argv[]and you wont see a difference. But code like:will give you an error - of invalid type conversion. That is due to a fact that defining an array on a stack requires to know the size of array during the compilation. But defining array as a function parameter - does not, the compiler in that case presumes that the stack manipulation is done in the caller function.