Not to sure how to do this

Started by
5 comments, last by scottdewald 17 years, 2 months ago
I was wondering if there is an easy way to copy one struct to another of the same datatype without having to make a conversion function in the struct. This is just an example, not my real code. The reason i ask is because i have about 30 structs that contain about 10 to 20 variables each so it will take me a good day or two to make the functions. Thanks in advance :)
struct vector_s
{
	float x, y, z;
};

struct plane_s
{
	int ID;
	vector_s Normal;
};

int main()
{
	plane_s *pPlanes = new plane_s;
	plane_s Planes1, Planes2;

	Planes1.ID = 1;
	Planes1.Normal.x = 1;
	Planes1.Normal.y = 0;
	Planes1.Normal.z = 0;

	Planes2.ID = 1;
	Planes2.Normal.x = 1;
	Planes2.Normal.y = 0;
	Planes2.Normal.z = 0;
	
	// Heres the part that is bad
	pPlanes[0] = Planes1;
	pPlanes[1] = Planes2;
	return 1;
}
Advertisement
By default, compiler will generate assignment operator and copy constructor for you (if you do not define your own). They will copy all data in your structs just as you need.
Note that if your structs contain pointers those methods will copy value of the pointer. They will not automatically allocate new data and copy arrays. Thus you need to take great care when freeing such data to prevent multiple deletes on one pointer.
Well, it compiles yes, but dosnt run. Crashed on startup and the debugger just stops at the line where im making the conversion. The only way iv been able to do it is:

pPlanes[0].ID = Plane1.ID;
pPlanes[0].normal.x = Plane1.normal.x;
pPlanes[0].normal.y = Plane1.normal.y;
pPlanes[0].normal.z = Plane1.normal.z;


i cant just do
pPlane[0] = Plane1;

Just wont work, dunno if i have to do something else or something.
int main(){        // Here you allocate room for A SINGLE plane_s	plane_s *pPlanes = new plane_s;        // snip	// Here you try to stuff TWO plane_s objects where there's only room for one	pPlanes[0] = Planes1;	pPlanes[1] = Planes2;        // ..and here you forget to delete what you new'd	return 1;}


What you SHOULD do:
#include <vector>// snipint main(){  std::vector<plane_s> planes;  // snip  planes.push_back(plane1);  planes.push_back(plane2);}


Wow, i wasnt even thinking about vectors. Il give it a try, thanks. /* tired */
Chapters 6 onward are relevant, if you want a proper understanding.
As was mentioned above, a default constructor will automatically be provided for you for structs and classes. This is usually sufficient as long as your struct/class doesn't allocate memory or open resources. You can simply assign the vector_s instance to the vector_s portion of the plane_s struct.
{  plane_s  Planes1;  vector_s Vector1;  // populate Vector1  Planes1.ID = 1;  Planes1.Normal = Vector1;}

Scott
www.slimcalcs.com
<a href="http://www.slimcalcs.com>www.slimcalcs.com

This topic is closed to new replies.

Advertisement