Re: Pointer to an array of pointers
Andy Gibbs <andyg1001@hotmail.co.uk> writes:
Hello!
Please could someone help me with what is probably a trivial problem, but is
definitely tying me in knots!
I have a class MyObject, and I need to create a pointer to an array of
pointers to this class. I think I am correct with the definition of...
MyObject* (*pointer)[];
which I take to mean a pointer to an array of MyObject pointers.
You can skip the array. A pointer is automatically a pointer to an array.
class MyObject {
public:
MyObject(){};
};
int main(){
MyObject** pointer;
pointer=new MyObject* [4];
pointer[0]=new MyObject();
pointer[1]=new MyObject();
pointer[2]=new MyObject();
pointer[3]=new MyObject();
delete pointer[0];
delete pointer[1];
delete pointer[2];
delete pointer[3];
delete [] pointer;
return(0);
}
/*
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Fri Feb 13 13:33:25
SRC="/tmp/a.c++" ; EXE="a" ; g++ -g3 -ggdb3 -o ${EXE} ${SRC} && ./${EXE} && echo status = $?
status = 0
Compilation finished at Fri Feb 13 13:33:25
*/
I believe I am also correct with my accessor function:
MyObject& item(int index) {
return *((*pointer)[index]);
}
Since you have an array of pointers, why do you want to return a reference?
However, I am having real difficulty working out how to use new and delete
with my pointer. So the following doesn't work:
pointer = new MyObject*[size];
for (int i = size; i-->0;)
(*pointer)[i] = new MyObject(...);
Because the first line fails compile with "cannot convert DbString** to
DbString*(*)[] in assignment". (I am using GCC 4.1.2.)
See the difference between your post and my answer. Your post doesn't
contain full source code, compilable. Mine does. If it had an error,
you could debug it.
The following use of delete compiles, but I am not sure it does what I think
(hope?) it does!
for (int i = size; i-->0;)
delete (*pointer)[i];
delete[] pointer; // should this be delete[] *pointer ?
No. You want to delete the memory pointed to by pointer, not by
*pointer (which is pointer[0]). See my code.
--
__Pascal Bourguignon__