c - How to copy a pointer to an element of an array with memcpy -
after executing code:
char **argv_p; char *argv[20] = { null }; memcpy(&argv_p, &argv, sizeof(argv_p));
argv_p
ends being null.
this because &argv decomposing pointer first pointer in argv array. using &argv[0]
yields identical results (as expected).
question is, whether there's syntax in c allow char ***
passed memcpy, without resorting hacky like
char **argv_p; char *argv[20] = { null }, **argv_start = argv; memcpy(&argv_p, &argv_start, sizeof(argv_p));
which have tested , produces correct result.
edit: know can straight assignment, working around const issues. bonus internet points if knows why execve
takes char * const *
instead of char const **
second argument.
edit edit: clarify, difference between consts:
char * const *
- makes contents of array immutable char const **
- makes contents of string buffers pointed array immutable.
const constifies thing left, unless appears first (the ansi c guys need shooting that) in case constifies thing on right. although many people write const char *
, it's considered best practice some, write char const *
because application of const consistent.
you can't cast away const without receiving warning c compiler. memcpy way work around without warnings.
many older libraries don't correctly mark arguments functions const, , if have applied const correctly types in code, compiler emit warnings. why using memcpy acceptable.
do not try work around const
copying pointer.
instead may necessary copy data pointer points to, , can point non-const data non-const pointer , compiler , optimizer.
aliasing pointer avoid qualifiers never acceptable, no matter how done, i.e. copying pointer variable different qualifiers not practice, , in cases may cause runtime errors or other undefined behaviour (e.g. in case const
qualifier causes referenced storage read-only, , alias (ab)used try modify storage).
where possible qualifiers should removed "upstream" avoid causing unnecessary clashes system libraries may not accept parameters qualifiers (c of course not allow possibility).
where absolutely necessary, , can shown not cause problems, acceptable use __unconst()
macro. if compiler target platform not offer 1 best solution define __unconst()
no-op , document potential warning may result acceptable (and show why).
Comments
Post a Comment