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 :(
The compiler has no information about the size of the array after passing them as pointer into a function. So you often need a third parameter: The size of the arrays to copy.
A solution (without any error checking) could be:
The easiest way is probably
although a solution with
memcpy()
will also work.That should do it:
EDIT: By the way: It will save a copy of
a
inb
.This has a feel of poorly masqueraded homework assignment... Anyway, given the predetermined call format for
copySolution
in the original post, the proper definition ofcopySolution
would look as followsNow, inside the
copySolution
you can copy the arrays in any way you prefer. Either use a cycleor use
memcpy
as suggested aboveOf course, you have to decide first which direction you want your arrays to be copied in. You provided no information, so everyone just jumped to some conclusion.
As Johannes Weiß says,
memcpy()
is a good solution.I just want to point out that you can copy structs like normal types:
In my case previous solutions did not work properly! For example, @Johannes Weiß's solution did not copy "enough" data (it copied about half of the first element).
So in case, somebody needs a solution, that will give you correct results, here it is:
Some notes, I used calloc for a, because in the '// filling a' part I was doing operations that required initialized data.