This is the prototype for execv
:
int execv(const char *path, char *const argv[]);
Can I pass an array of const char
pointers as the second argument?
This example program gives a warning when USE_CAST
is not set:
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc > 0) {
const char *exe_name = "/bin/echo", *message = "You ran";
const char *exe_args[] = { exe_name, message, argv[0], NULL };
#ifdef USE_CAST
execv("/bin/echo", (char **) exe_args);
#else
execv("/bin/echo", exe_args);
#endif
}
return 0;
}
When compiling, gcc says, "passing argument 2 of 'execv' from incompatible pointer type" if I don't use the cast.
From the POSIX documentation for execv
(halfway through the Rationale section), it looks like the second argument is a char *const
array only for backwards compatibility:
The statement about
argv[]
andenvp[]
being constants is included to make explicit to future writers of language bindings that these objects are completely constant. ... It is unfortunate that the fourth column cannot be used...
where the "fourth column" refers to const char* const[]
.
Is the (char **)
cast safe to use here? Should I create a char *
array and pass that to execv
instead?