Re: 2dimensional array
Mike wrote:
Hi Stuart
struct Pos
{
int x, y;
};
//...
Pos pos;
pos.x = 3;
pos.y = 4;
Thanks how would that look as a pointer?
I'm assuming you mean something like this:
Pos *pos = new Pos;
pos->x = 3;
pos->y = 4;
//...
delete pos;
But I wouldn't recommend doing it that way, for at least two reasons:
(1) Setting the individual elements of *pos like this seems
unnecessarily long. Pos is crying out for a constructor:
struct Pos
{
int x, y;
Pos(int x_, int y_) : x(x_), y(y_) {}
};
Pos *pos = new Pos(3,4);
//...
delete pos;
(2) Managing your memory manually like this makes getting your code to
work properly in the presence of possible exceptions pretty difficult.
You'd be better off using something like shared_ptr:
shared_ptr<Pos> pos(new Pos(3,4));
I've something like:
class droplet{
private:
COORD pos;//location of drop head on screen
int speed;//speed
public:
//constructor, takes a coordinate and a speed
droplet(int x, int y, int spd){
pos.X=x;
pos.Y=y;
speed=spd;
}
If you give COORD a constructor, you can (/should) rewrite this to use
initialization:
droplet(int x, int y, int spd)
: pos(x,y), speed(spd)
{}
I get an error (does not name a type) with GCC here: COORD pos;//
location of drop head on screen
and here:
pos.X=x;
pos.Y=y;
Where is COORD defined? You need to post your actual code rather than
snippets (a minimal "compileable" example -- although obviously in this
case the problem is that it won't actually compile, so post the code
you're expecting to compile instead).
then in main()
droplet **drops = new droplet * [num];//declare a pointer of a
droplet pointer and sets it to an array of droplet pointers
for(int i=0;i<num;i++)
drops[i] = new droplet(x,y,spd);
Why all the dynamic memory allocation? It looks like you might well be
better off with something like:
std::vector<droplet> drops;
drops.reserve(num);
for(int i=0; i<num; ++i) drops.push_back(droplet(x,y,spd));
I think you might need a better book -- which one (if any) are you using
at the moment? It seems to be making your life harder than is necessary...
Cheers,
Stu
so i could later do such:
if(!(pos.Y-i<-1||pos.Y-i>SCREEN_HEIGHT-2))
Many thanks again
Michael