The code I'm working on is largely C++ but calls out using c system calls because unix. In C++ a string literal is a const char[]
, as far as I know because they are stored in the text segment and you don't want to modify them. If I'm going to be passing a list of arguments to say execv()
, which takes char * const argv[]
what's the correct way to declare it so no warnings are produced and no excessive casting occurs?
char * args[] = {"foo", "--bar", "bazz", NULL};
Is clear notation and makes sense but I think ends up with casting every literal from a const char[]
to a char *
. Which isn't ideal or maybe even memory safe.
char args[4][6] = {"foo", "--bar", "bazz", "\0" };
Puts all the variables in the stack, but everything else is wrong. It isn't an array of char*. NULL can't be set as the last entry. It can't be passed to another function unless that function also knows the exact dimensions. It wastes space. It doesn't accept dynamic elements easily. And it takes intense policing of the dimensions.
char arg0[] = "foo";
char arg1[] = "--bar";
char arg2[] = "baz";
char * args[] = { arg0, arg1, arg2, NULL};
Should work I think but it's a really verbose way to do this. Also it takes matching changes in two locations to update which is less than ideal for maintenance.
What's the right way to do this?