Pointers to classes

I have an array of classes. The size of the array is unknown. For this, I used a pointer as follows.
1
2
3
4
5
6
myclass *ptr;
myclass var1, var2, var3; // test variables
ptr = new myclass;
*ptr = var1;
*(ptr+1)=var2;
*(ptr+2)=var3;


Is this legal ? or do i need to include another line ptr+1=new myclass;
This is legal syntax, but it is illegal in that it will cause memory corruption (arguably the worst thing you can do).

*(ptr+1) = var2; is the same thing as ptr[1] = var2. What you're doing is you're trying to set the 2nd object in the array. The problem is, there ISN'T a second object in the array -- you only created one object.

If you want 3 objects, then allocate 3 of them:

1
2
3
4
5
6
7
8
9
10
ptr = new myclass[3];  // make 3

*ptr = var1;   // now this will all work
*(ptr+1)=var2;
*(ptr+2)=var3;

*(ptr+3)=var4;  // but this is bad!  There isn't a 4th!

// also, don't forget to delete[] what you made with new[]
delete[] ptr;
The size of the array is unknown

Use a vector; they're dynamic, so you can append and... de-append (?) (or std::vector::push_back() and std::vector::pop_back()) as much as you want as long as you don't try to pop_back() a 0-size vector or something.

As for whether or not you can actually do what you're trying to do above, I'm not sure what exactly you're trying to do.

FUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
Last edited on
Woah, I missed the whole "size of the array is unknown" bit.

You're better off with vector or list or something in that case. Just add new items as needed.
What does OP mean by "the size of the array is unknown"? That the final size is unknown, or that he receives an array of unknown size?
I am attempting a branched linked list. Each node can have arbitrary number of branches (Not a binary tree). The actual structure would be defined in main(). Disch: I think you are right, in my current implementation, i think there are some problems which i suspect are due to the memory corruption. If i define a tree in a particular order, things work out fine. But if the same topology is defined in a different order, the stored data gets corrupted.

Perhaps i should use try vectors. That should work.
That's called an n-ary tree. Lists have no branches.
Last edited on
Alright. Now i know what it is called. thanks.
Topic archived. No new replies allowed.