Reputation: 63
I have two char ** variables :
char ** a;
char ** b;
with a
containing a bunch of char arrays and so does b
, after reallocing the memory of a
, I wanted to append it with b char arrays, as it showen below:
memcpy(a + oldSizeOfA, b, sizeOfB);
I'm expecting that all of the char arrays in b
will be in a
, what am I doing wrong ?
I tried to simplify my code to this :
char ** a = (char **)malloc(5*sizeof(char*));
char ** b = (char **)malloc(10*sizeof(char*));
for (i = 0; i < 5; i++)
{
b[i] = (char *)malloc(4);
strcpy(b,"tes");
a[i] = (char *)malloc(4);
strcpy(a,"tes");
}
memcpy(&a + 5, &b, 5);
Upvotes: 0
Views: 926
Reputation: 241901
If you want to copy five elements from the array b to the five positions starting at index 5 in array a, you don't want:
memcpy(&a + 5, &b, 5);
It should be
memcpy(a + 5, b, 5 * sizeof(*b)); // See Note below
That's independent of the type of what a
and b
point to.
But note that if a
and b
point to pointers, then only the pointers are being copied. So if a
and b
are arrays of character strings -- char**
-- then you'll end up with a[5]
being the same pointer as b[0]
. That might be fine, but it could also be a problem. For example, if you modify some character in b[0]
, the string pointed to be a[5]
(which is the same string) will also be changed. And, critically, if you free(b[0])
, then a[5]
is no longer a valid pointer, so you cannot refer to it or free
it.
Not copying the character strings can save you a lot of memory, but the memory sharing comes at a huge price in bookkeeping. It's often simpler to make new strings, which means that you need to use something like strdup
(or you could write out the malloc
and the strcpy
, but strdup
is less bug-prone).
a
and b
are variables with addresses. &a
and &b
are the addresses of the variables. Since a
is a scalar variable, &a + 5
is undefined behaviour. It points at somewhere else in your function's local stack frame (if the stack frame is big enough), which means to some other local variable. But you don't know which variable, and you don't have any right to describe it that way, even if you knew which one it was.
What you're interested in is the address of the sixth slot in the array a
points at, which is a + 5
(thanks to C pointer arithmetic) or &a[5]
, which many people would say is clearer.
Also, like malloc
, memcpy
counts in bytes, not elements (since it doesn't know the element size). So a count of 5 means "5 bytes", which you'll find is a lot less than five pointers. (Indeed, it's probably less than one pointer.)
Upvotes: 2