问题
I'e been trying for sometime to concatenate some struct (I defined) type variables into a bigger one. What I got is basically like this:
I have a struct and two variables of type struct**. I declare a third one struct C and I want to concatenate A and B into C. What I tried is something like this (I don't have the code in front of me right now so I'll write something very similar with some names changed as I don't remember them.
struct** A, B;
struct** C;
(I know A and B as I receive them by calling another function)
I allocate memory for C like this.
C = (struct**)malloc(sizeof(A)+sizeof(B));
And I move A and B with memcpy like this.
memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &C, sizeof(B));
It's obvious that what I've done is not correct as it seems after all of this C contains only A. I'm pretty sure the problem is from "**", I can't handle pointers to pointers that well. Can anybody give me some advice regarding my issue? I also don't want to use Handles, I have to use memcpy/memmove.
[update from comment:]
My struct are all the same type.
回答1:
You already have a struct A a; and a struct B b; defined somewhere.
To concatenate them into a struct C you do this:
struct A a;
struct B b;
struct C{
struct A a;
struct B b;
};
struct C c;
c.a = a;
c.b = b;
No pointers or memcpy required.
Edit: Since a and b are of the same type you can somewhat shorten it to this:
struct Something a, b;
struct C{
struct Something[2];
};
struct C c;
c[0] = a;
c[1] = b;
In C++ you would do something like this:
using C = std::array<Something, 2>;
C c{a, b};
回答2:
Just user an array.
Assuming struct A is defined an array on the stack
struct A a1 = {...}; /* some initialisation here */
struct A a2 = {...}; /* more initialisation here */
struct A a[2];
a[0] = a1;
a[1] = a2;
or allocate it dynamically:
struct A * pa = malloc(2 * sizeof *pa);
if (NULL != pa)
{
pa[0] = a1;
pa[1] = a2;
/* use pa */
free(pa);
}
else
{
/* handle malloc error */
}
回答3:
Well, first off, your code has a bug:
memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &C, sizeof(B));
Should probably be
memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &B, sizeof(B));
You were copying C back into C rather than B.
Second, if you ever find yourself playing with pointers like this you've probably got a design problem somewhere along the lines. If you REALLY want to merge two structs together, why not have struct C simply contain both struct A and B?
If you REALLY want struct C to have nothing bot primitives, dude, just do the work to assign each field individually. Is it really all that much work? I guess it makes sense to generalize it if you expect these fields to change a lot. But this sort of "clever code" is the exact sort of things which will bite you in the ass later down the line.
来源:https://stackoverflow.com/questions/32315785/how-can-i-concatenate-two-structs-type-variables-in-c