c - Copying one structure to another -


i know can copy structure member member, instead of can memcpy on structures?

is advisable so?

in structure, have string member have copy structure having same member. how do that?

copying plain assignment best, since it's shorter, easier read, , has higher level of abstraction. instead of saying (to human reader of code) "copy these bits here there", , requiring reader think size argument copy, you're doing plain assignment ("copy value here here"). there can no hesitation whether or not size correct.

also, if structure heavily padded, assignment might make compiler emit more efficient, since doesn't have copy padding (and knows is), mempcy() doesn't copy exact number of bytes tell copy.

if string actual array, i.e.:

struct {   char string[32];   size_t len; } a, b;  strcpy(a.string, "hello"); a.len = strlen(a.string); 

then can still use plain assignment:

b = a; 

to complete copy. variable-length data modelled though, not efficient way copy since entire array copied.

beware though, copying structs contain pointers heap-allocated memory can bit dangerous, since doing you're aliasing pointer, , typically making ambiguous owns pointer after copying operation.

for these situations "deep copy" choice, , needs go in function.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -