Simple question on C: Copying variables of user defined struct type
This ought to simple. Say we have a struct from a lib开发者_StackOverflow中文版rary that doesn't offer copying facilities. Is there an easy way to copy a variable of the type of that struct to a new variable of the same type without doing assignments for each of its sub members? Or does one have to be making special copying functions?
Well, struct types are assignable in C:
struct SomeStruct s, d;
...
d = s;
It doesn't matter, where they are defined. And there's no need to copy "each of the sub members". Where did you even get the idea about copying it member by member?
Of course, the assignment will perform shallow copying only. If you need deep copying, you need a library-provided copying routine. If there's none, you will have to implement it yourself. In order to do that you will need full knowledge of the actual deep-memory organization of the structure. If you don't know it (i.e. if it is not documented), you are out of luck - proper deep-copying is impossible.
This sounds like the classic deep copy vs shallow copy topic.
You could copy the variable (shallow copy) with a memcpy operation.
If the struct holds references to other varibles, then this might not be enough and you should implement a more sofisticated (deep) copy.
C supports struct assignment natively, so if a per-member copy is safe/effective, you can just use direct assignment:
typedef struct {
int v1, v2;
float f1;
} A;
A a = { 0, 2, 1.5f };
A b;
b = a;
It has already been explained that one may use simple assignment for structs, but perhaps an interesting characteristic of this technique is that it even allows you to copy structs containing arrays despite arrays being unassignable. More importantly, it demonstrates that it is not always possible to copy a struct just by assigning to its members individually.
For example:
typedef struct {
char data[100];
} string;
string a = {"Hello world!"};
string b;
b = a; // works!
puts(b.data); // writes "Hello world!" to standard out.
b.data = a.data; // oops, doesn't work!
Keep in mind that it might not be safe to do per-member copy of a structure; for instance, it may hold pointers, and just copying those pointers might not be a great idea if you want an actual copy of the data. However, when it is safe to do it, you may use memcpy
save yourself some keystrokes.
struct foo a, b;
// let the third-party lib fill the struct
thirdPartyLibraryCallInvolvingTheFooStruct(&a);
// now we want to copy a to b
memcpy(&b, &a, sizeof b);
Don't forget to read the manpage for more infos!
You could use the memcpy function. This sets a contiguous area of memory, just copying bit for bit; ignoring whether it's a series of ints, or a char array, or whatever.
精彩评论