How can I concatenate two variables of type structs in C ++?
I was trying to somehow combine some variables of type struct (I defined) into a larger one. I got basically like this:
I have a structure and two variables of type struct **. I am declaring a third structure C, and I want to merge A and B into C. What I have tried is something like this (I don’t have any code right now, so I will write something very similar with some changed names, since I don't remember them.
struct** A, B;
struct** C;
(I know A and B when I get them by calling another function)
I am allocating memory for C like this.
C = (struct**)malloc(sizeof(A)+sizeof(B));
And I move A and B with memcpy as follows.
memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &C, sizeof(B));
Obviously what I did is wrong, as it seems like all of this C contains only A. I'm pretty sure the problem is with "**", I can't handle pointers to pointers that well. Can anyone give me some advice regarding my problem? I also don't want to use Pens, I need to use memcpy / memmove.
[update from comment:]
My structure is of the same type.
source to share
You already have struct A a;
and struct B b;
. To combine them into struct C
, you do the following:
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
.
Edit: Since a
and b
are the same type, you can shorten it somewhat 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};
source to share
Just a custom array.
Assuming struct A
an array is given 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 */
}
source to share
Well, first of all, your code has an error:
memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &C, sizeof(B));
Probably,
memcpy(&C, &A, sizeof(A));
memcpy(&C + sizeof(A), &B, sizeof(B));
You copied C back to C, not B.
Secondly, if you've ever played with pointers like this, you probably have a design issue around here. If you REALLY want to concatenate two structures together, why shouldn't a C structure just contain both struct A and B?
If you really want the C struct to have nothing primitive bots, dude, just do the work to assign each field separately. Does it really work that much? I guess it makes sense to generalize it if you expect these fields to change a lot. But that kind of "smart code" is the exact kind of thing that will bite your ass later down the line.
source to share