I can see a small mistake.
galaxyobjectsptr = new galaxyobject[ galaxyobjectstotal];
// set to null
cout << "\r\nSet up initial values to galaxy objects as null...";
for(int i=0; i<= galaxyobjectstotal; i++)
I quoted more code than the mistake itself (which is underlined
) in order to provide context.
As you know, in C and C++ counting starts from 0, not 1.
This means that an array A
that has 3 elements will provide A
It is important to notice that A
does not exist.
Trying to access A
means that you're going out of bounds. This is undefined behavior, which in turn means that any of these things can happen randomly:
it works and you get 0
it works and you get a garbage value (e.g. -68476)
it crashes with a segmentation fault
So you are allocating an array of length galaxyobjectstotal
This means that the the index i
of the for()
loop can go as high as (galaxyobjectstotal - 1)
and no higher.
for(int i=0; i < galaxyobjectstotal; i++) // same as
for(int i=0; i <= galaxyobjectstotal - 1; i++) // but the above is preferred by most people
|Anyway, I am writing code that creates a dynamic array. I would like to be able to do something like|
galaxyobject[object] -> uniqueid = in the class but I do not think I have it setup right.
From what I see, you already figured out that the correct form is:
Also don't forget to put a
somewhere, perhaps in the destructor.