I want to declare a global array of objects, but i don't know how many objects there will be until later in the program. how would i do this?
thanks
Printable View
I want to declare a global array of objects, but i don't know how many objects there will be until later in the program. how would i do this?
thanks
you declare a pointer to the object.
to allocate an deallocate memory dynamically you use new and delete.
ex
obj* g_myobjarray;
..
g_myobjarray=new obj[x];
..
delete[] g_myobjarray;
Or you declare an STL vector, which is easier to use.
say i do something like this:
Obj *myObj;
myObj = new Obj[10];
Now, myObj is a pointer right? So if I wanted to pass the array byref to a function, would i have to pass the memory address of the pointer myObj to a function that accepted the value as another pointer? Like:
void blah(Obj *pointer) {}
blah(&myObj)
or could I just pass the pointer myObj and not the mem address? Also, is there any way for 'blah' to tell the upper bound of the array that was passed? What is the correct argument syntax for passing an array?
thanks
jmiller
I suggest you do as CB suggested and have a look at the vector if you want a fast and easy solution, if you're practicing C++ arrays, pointers and references can be very useful to understand
myObj is a pointer to the first object in the array, if you want to reassign or resize the array you'd better pass the pointer by reference, Obj *&pointer, and when you declare a reference, you don't have to use the addressof operator, so
void blah(Obj *&pointer) {}
..
blah(myObj);
if you only want to change or access of the array elements, you could just pass the pointer, but you cannot change the pointer (you can but only in this scope.)
void blah(Obj *pointer) {}
..
blah(myObj);
The size of the array has to be passed as well in a separate variable, if you intend to resize it. Remember for each new you have to use delete, and be cautious to new and delete in separate scopes, you'll easily end up with memory leaks, its not considered as good programming to do so.