c array concatenation problem
I'm trying to concatenate an array with the array from argv (I forgot the formal name for that, input a开发者_开发问答rray? parameter array?)
anyway, I initalize the original array, then I use memcpy
to copy the two arrays into the new array.
int main(int argc, char *argv[]) {
char *args1[] = {"foo","bar"};
char **args = (char**) calloc(argc, sizeof(char*));
memcpy(args, args1, sizeof(char*) * 2);
memcpy(args + sizeof(char*) * 2, argv+1, sizeof(char*) * (argc-1));
but when I run this
printf("%s %s %s\n", args[0], args[1], args[2]);
and then run
./test baz
I get a result of
foo bar (null)
So I'm trying to figure out where my second memcpy screwed up, but I can't find it. Any help? Thanks in advance.
There are two problems in this code.
Problem #1
calloc(argc, sizeof(char*))
should be
calloc(argc + 2, sizeof(char*))
Problem #2
You are confusing pointer arithmetic. This part
args + sizeof(char*) * 2
should simply be
args + 2
Alternatively, you could use
&args[2]
Either way, don't multiply the offset by the size of the type. The compiler does that automatically.
精彩评论