Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

to copy a structure to another structure 1

Status
Not open for further replies.

kemsa

Programmer
Feb 8, 2005
3
0
0
DK
Hello,

I'm making a program with a structure. I would like to copy SOME of the elements in the structure to another structure, fx if it fulfill some criteria. The program could be something like:

struct vehicles
{
const char *name;
const int year;
};

struct vehicles car[] =
{
{"Mercedes", 2004}, {"BMW", 2002}, {"Mazda", 2004},
{"Fiat", 2001}, {"Toyota", 1999}, {"Passat", 2000},
{"Mitsubishi", 1996}, {"Honda", 1991}, {"Jaguar", 2002} };

lets say that i had another structure like this:

struct newVehilcles
{
const char *name;
const int year;
}newCar[];

and I wanted to copy car[] to newCar[]. How do I do.
Joy..
 
Then you need to copy each member seperately if the structures are different.

Code:
for ( i = 0 ; i < n ; i++ ) {
  newCar[i].name = car[i].name;
  newCar[i].year = car[i].year;
}

But beware of directly copying a pointer from one place to another - you get two pointers to the SAME bit of memory, so changing the memory via one pointer will change what is seen via the other pointer.
This is what is referred to as a shallow copy.

This isn't a problem while you're using string constants (as in this example), but would be if you were reading from a file and allocating memory for each car name.

Deep copies duplicate all the allocated memory as well, thus insulating you from changes to one being seen by the other.

--
 
These strctures have pointers in them, so they require deep copy.

like following
for ( i = 0 ; i < n ; i++ ) {
newCar.name = string_dup (car.name);
newCar.year = car.year;
}

thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top