Hi
I just got feedback from my teacher and he gave a comment for the following piece of code:
1 2 3 4 5 6 7
|
void IOclass::printDice( vector<Die> diceVec)
{
int diceToPrint[diceVec.size()];
.
.
.
}
|
He pretty much said that my compiler must be very forgiving to let that slide. Since the compiler doesn't know the size of diceVec and therefore can't decide the size needed to allocate the array. He also recommends that I instead should use dynamic memory allocation:
int[] diceToPrint = new int[diceVec.size()];
I'm not sure why my way shouldn't work since my compiler (GNU GCC Compiler) lets it through without warning or error. The diceVec is sent to the function and I though that vectors had this size() function so one could do things like this? I've also tried printing diceVec.size() and I get the number of elements in diceVec printed with no problems.
If I were to use the suggested dynamic way I need to delete the array diceToPrint to avoid memory leak right? When should this be done, right before I exit the function?
And this is how I would do it:
delete diceToPrint;
right?
I would ask my teacher but since it's weekend I'll try the forum out first :)
Thanks in advance!
EDIT: I should say that I tried what my teacher proposed but didn't get it to work. I tried
1 2 3 4 5 6 7 8
|
void IOclass::printDice( vector<Die> diceVec)
{
int[] diceToPrint = new int[diceVec.size()];
// ...
// some code
// ...
delete diceToPrint;
}
|
Ironically the error I get is:
error: initializer fails to determine size of 'diceToPrint'
AND
error: type '<type error>' argument given 'delete', expected pointer