Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying arrays of structs in C

Tags:

arrays

c

struct

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 :(

like image 928
Víctor Avatar asked Nov 07 '09 17:11

Víctor


People also ask

How do you copy an array to a struct?

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.

How does C Copy structs?

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 .

Can you copy an array in C?

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.

Can structs 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.


2 Answers

That should do it:

memcpy(&b, &a, sizeof(a));

EDIT: By the way: It will save a copy of a in b.

like image 176
Johannes Weiss Avatar answered Oct 12 '22 21:10

Johannes Weiss


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] */
}
like image 34
pmg Avatar answered Oct 12 '22 19:10

pmg