Assigning an address to an object pointer

I have the following code.

1
2
StackElement *StackElementArray;
StackElementArray = new StackElement[iMaximumDepth];


I want to assign one element of this array StackElementArray the address of another object. For example,

1
2
3
4
5
void	StackMem::push(StackElement &iStackElement)
{
	CurrentDepth++;
	StackElementArray[0] = iStackElement;
}


The StackElement class contains pointers to some dynamic arrays. When I use the assignment, StackElementArray[0] = iStackElement;, it doesn't copy the complete contents and I have to define an 'assignment operator' function to copy all the contents. I am wondering if there is a way I can assign StackElementArray[0] the pointer to the StackElement object. In that case, I will not need to copy the contents of iStackElement into StackElementArray[0] and will just copy the address.
Not unless your StackElementArray is an array of pointers:

You can't assign an address of object A to object B. You can however assign an address of object A to pointer B (since that's what pointers do).

Perhaps it might make more sense to make an array of pointers instead?



Also... any reason why you're doing your own memory management? This is much easier/safer if you use STL containers.
Thanks for your reply @Disch.

Not unless your StackElementArray is an array of pointers:


That's what was in my mind. But, when I googled it, what I gathered was that StackElementArray is actually an array of pointers. For example, see the following

http://stackoverflow.com/questions/5887615/creating-an-array-of-object-pointers-c

Can you please give a brief example how to create an array of pointers?

Also... any reason why you're doing your own memory management? This is much easier/safer if you use STL containers.

It is because I need ordered stack and that I couldn't find in C++. My requirements are push, pop functions along with an extra sort() function that sorts the stack at any point I want wrt some variable of the object.
Last edited on
There is a large difference between 'array of pointers', 'pointer to array', 'pointer to first element in array', 'pointer to array of pointers', and 'pointer to first element in array of pointers'.

I believe you will want 'pointer to first element in array of pointers':
1
2
3
//Notice the difference from yours
int **p = new int*[10];
//pointer to first element in an array of 10 pointers to int 


aitezaz wrote:
> Also... any reason why you're doing your own memory management? This is much easier/safer if you use STL containers.

It is because I need ordered stack and that I couldn't find in C++. My requirements are push, pop functions along with an extra sort() function that sorts the stack at any point I want wrt some variable of the object.
There are multiple STL classes that are suitable to this. Have you researched the STL?
Last edited on
Topic archived. No new replies allowed.