1

I'm trying to concatenate an array with the array from argv (I forgot the formal name for that, input array? 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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

sigh. I know my pointer arithmetic, so it was silly of me to make that kind of error and not notice it. That's the last time I take pointers from rosettacode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.