yes and no.
yes, that is the correct syntax.
No, you cannot just re-allocate a pointer as in your second post.
so if you have a pointer that you allocated and it is full of data, you cannot reallocate that. You MUST do that with these steps:
1) create a new pointer with the new size.
2) copy the data into the new pointer's location(s)
3) delete the original pointer
4) copy the address (pointer variable) of the new one to the old one.
some of the reasons for this...
every new must be paired to a delete. if you do this:
x = new something; //pretend x is now assigned memory location 1
x = new something; //pretend x is now assigned memory location 2
you lost memory location 1 and have no way to delete it because you have not stored it anywhere. That is why you need the second variable and all the juggling.
also, memory for pointers is allocated back to back and there is no way to know that if the computer gives you 10 locations that the 11th will be free to use later; something else in your program or another program could take control of that location. The only way to be SURE is to allocate 11 locations elsewhere and move the data from the 10 to the 11.
so explicitly to resize pkingdom here you need:
1 2 3 4 5 6
|
Kingdom *tmp = new Kingdom[count+1]; //this is your count+1 correct syntax being used correctly
for(j = 0; j < count; j++)
tmp[j] = pKingdom[j]; //if you do not have an assignment operator for this, you have to copy each class field one by one here.
delete [] pKingdom;
pKingdom = tmp;
|
I can't stress enough that vectors do this for you using tools of the language so you don't have to keep reinventing, debugging, and dealing with this. Vectors do a lot of other stuff, but this feature coupled with their assignment operator are the top 2 in my eyes.