It's been a long since I don't use C language, and this is driving me crazy. I have an array of structs, and I need to create a function which will copy one array to another (I need an exact copy), but I don't know how to define the function call. I guess I need to use pointers, but when I try it gives me an error.
struct group{
int weight;
int x_pos;
int y_pos;
int width;
int height;
};
struct group a[4];
struct group b[4];
copySolution(&a, &b);
That last declaration send me an error. As I said, it's been a long since programming in C, so I'm a bit lost right now :(
1) Add a declaration structure * pStructure; to your code. 2) Add pStructure = (structure *) array; ` right after array's declaration. 3) Then, at the line where the memcpy is, set a breakpoint.
For simple structures you can either use memcpy like you do, or just assign from one to the other: The compiler will create code to copy the structure for you. An important note about the copying: It's a shallow copy, just like with memcpy .
Copying an array involves index-by-index copying. For this to work we shall know the length of array in advance, which we shall use in iteration. Another array of same length shall be required, to which the array will be copied.
We can also use assignment operator to make copy of struct. A lot of people don't even realize that they can copy a struct this way because one can't do same it with an array. Similarly one can return struct from a function and assign it but not array.
That should do it:
memcpy(&b, &a, sizeof(a));
EDIT: By the way: It will save a copy of a
in b
.
As Johannes Weiß says, memcpy()
is a good solution.
I just want to point out that you can copy structs like normal types:
for (i=0; i<4; i++) {
b[i] = a[i]; /* copy the whole struct a[i] to b[i] */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With