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 (
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:
int i, n = 50;
struct YourStruct *a, *b;
a = calloc(n, sizeof(*a));
b = malloc(n * sizeof(*b));
for (i = 0; i < n; ++i) {
// filling a
}
memcpy(b, a, n * sizeof(*a)); // <----- see memcpy here
if (a != NULL) free(a);
a = calloc(n*2, sizeof(*a));
memcpy(a, b, n * sizeof(*b)); // <------ see memcpy here again
Some notes, I used calloc for a, because in the '// filling a' part I was doing operations that required initialized data.
The easiest way is probably
b=a
although a solution with memcpy()
will also work.
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:
void copySolution(struct group* a, struct group* b, size_t size) {
memcpy(a, b, size * sizeof(*a));
}
That should do it:
memcpy(&b, &a, sizeof(a));
EDIT: By the way: It will save a copy of a
in b
.
This has a feel of poorly masqueraded homework assignment... Anyway, given the predetermined call format for copySolution
in the original post, the proper definition of copySolution
would look as follows
void copySolution(struct group (*a)[4], struct group (*b)[4])
{
/* whatever */
}
Now, inside the copySolution
you can copy the arrays in any way you prefer. Either use a cycle
void copySolution(struct group (*a)[4], struct group (*b)[4])
{
const struct group *pb, *pbe;
struct group *pa;
for (pa = *a, pb = *b, pbe = pb + sizeof *b / sizeof **b;
pb != pbe;
++pa, ++pb)
*pa = *pb;
}
or use memcpy
as suggested above
void copySolution(struct group (*a)[4], struct group (*b)[4])
{
memcpy(b, a, sizeof *b);
}
Of 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:
for (i=0; i<4; i++) {
b[i] = a[i]; /* copy the whole struct a[i] to b[i] */
}