tags:

views:

173

answers:

4
+7  A: 

You have no choice but provide a copy function yourself:

void copy_person(person *dst, const person *src)
{
    dst->name = malloc(strlen(src->name) + 1);
    dst->surname = malloc(strlen(src->surname) + 1);
    strcpy(dst->name, src->name);
    strcpy(dst->surname, src->surname);
}

which may be more elaborated than that: checking for errors, factoring the strlen + strcpy in an auxilliary function, etc.

That's what copy constructors in C++ are for.

Alexandre C.
If you are on a POSIX system (e.g linux), you could just use `strdup` instead of the `malloc + strcpy`.
Jens Gustedt
@Jens: that's what I had in my head when I wrote "factoring .... in a auxilliary function".
Alexandre C.
+3  A: 

Yes, copying struct that contain char arrays will work without any problem, but struct with char pointers (or any type of pointer for that matter) you will have to do manually.

Also note that the cast of malloc's return type is not needed in C (it is in C++) and can hide a missing prototype for malloc.

schot
A: 

You have to allocate memory to any pointer if you want to do a copy. However you can always make a pointer point to already allocated memory. For example you can do the following:

p2.name = p1.name (p1.name is already allocated memory)

This is dangerous as there are more than one references to the same memory location. If you free either p1.name or p2.name, it results in a dangerous situation. In order to copy the entire content you have to allocate memory to the pointers of the struct p2.

p2.name = <allocate memory>
copy individual struct members instead of a memcpy of the entire struct

This is because memory is not allocated in a contiguos manner. Also sizeof(struct) will give you size of the members of the struct and not the memory allocated to it.

For example sizeof(p2) = 8 = sizeof(p1)= sizeof(person) even after allocating memory to members of p1.

It would be a different case had the members been char arrays .

Praveen S
+1  A: 

A bit out of the box thinking:

Since the structure of your struct is static, you coukl write a small utility program or script to generate the copy code for you.

Take the source-code of your struct definition as input, and then devise a set of rules to generate the copying code.

This is quickshot, i don't know if it were faster to just write the copy-code manually - but at least it is a more interesting problem.

sum1stolemyname