Archived

This topic is now archived and is closed to further replies.

Arrays, pointers, and classes!

This topic is 5150 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello! I have a C++ question and I was hoping someone here would answer it for me! I have a class called cPS. It has all these different member variables and functions, but I'm only putting the important ones here.

class cPS
{
public:
	int maxnum;
	c_particle *part;

	void init(int max);
	void destroy(void);
};
 
I also have the class c_particle which has the member variables x, y, and z. What I need to do is create a new array and make *part point to it. Here are the init and destroy functions for cPS
void cPS::init(int max)
{
	this->maxnum=max;

	this->part= new c_particle[maxnum];

	for(int i=0; i<=this->maxnum; i++)
	{
		(this->part+i)->x=this->x;
		(this->part+i)->y=this->y;
		(this->part+i)->z=this->z;
	}
}

void cPS::destroy(void)
{
	delete [] this->part;
}
 
I think you can see what I'm trying to do. When the destroy function is called I get some kind of error. I think the problem has something to do with the accessing array elements in the for loop of the init function. Am I doing something wrong? [edited by - noname12345 on November 12, 2003 6:00:45 PM]

Share this post


Link to post
Share on other sites
The for loop your using looks like this:


for(int i=0; i<=this->maxnum; i++)


The conditional part is wrong. It will loop up to and including the maxnum index. Your array indexes are only from 0 to maxnum-1. So the for loop should look like this:


for(int i=0; i<this->maxnum; i++)


I hope that''s the problem...
-Shags

Share this post


Link to post
Share on other sites
quote:
Original post by merlin9x9
Well, if you use std::vector instead of dynamically-allocated arrays, you won''t even have to worry about having done something wrong.


That''s not quite true. The way he had his for loop coded would have borked up a std::vector just as easily.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
true BUT this is a beginner thread which might be a tad bit over the posters head. S/he should work out his/her issues and under stand the basic concepts before moving on to utilities such as STD

Share this post


Link to post
Share on other sites