After executing this code:
char **argv_p;
char *argv[20] = { NULL };
memcpy(&argv_p, &argv, sizeof(argv_p));
argv_p
ends up being NULL.
This is because &argv is decomposing into a pointer to the first pointer in the argv array. Using &argv[0]
yields identical results (as expected).
Question is, whether there's syntax in C that would allow a char ***
to be passed to memcpy, without resorting to something hacky like
char **argv_p;
char *argv[20] = { NULL }, **argv_start = argv;
memcpy(&argv_p, &argv_start, sizeof(argv_p));
Which I have tested and produces the correct result.
Edit: I know you can do straight assignment, but this is for working around const issues. Bonus internet points if anyone knows why execve
takes a char * const *
instead of a char const **
as its second argument.
Edit Edit: To clarify, the difference between the consts:
char * const *
- makes the contents of the array immutable
char const **
- makes the contents of the string buffers pointed to by the array immutable.
Const always constifies the thing to the left, unless it appears first (the ANSI C guys need shooting for that) in which case it constifies the thing on the right. Although many people write const char *
, it's considered best practice by some, to write char const *
because then application of the const is consistent.
You can't cast away a const without receiving a warning from the C compiler. memcpy is the only way to work around this without warnings.
Many older libraries don't correctly mark arguments to their functions as const, and if you have applied const correctly to types in your code, the compiler will emit warnings. That is why using memcpy is occasionally acceptable.