Home > Back-end >  Novice c for help
Novice c for help

Time:09-24

Topic: the topic is: let me fill in the code in the red place, release the p points to the node, the answer is the delete [] p; But I don't know why to add [], p is not an array...
# include
using namespace std;
Const int Size=5;
The class Stack;
The class Item {
Public:
The Item (const int & amp; Val) : the item (val) {};
Private:
Int item;
Item * next;
Friend class Stack;
};
The class Stack {
Public:
The Stack () : top (NULL) {}
~ the Stack ();
Int the Pop ();
Void Push (const int&);
Private:
Item * top;
};
Stack: : ~ Stack () {
Item * p=top, * q;
While (p!=NULL) {
Q=p - & gt; Next;
delete [] p;
P=q;
}
}

Int Stack: : Pop () {
Item * temp;
Int ret.
Temp=top;
Ret=top - & gt; The item;
Top=top - & gt; Next;
The delete temp.
Return ret.
}

Void Stack: : Push (const int& Val) {
Item * temp=new Item (val);
Temp - & gt; Next=top;
Top=temp;
}
Int main () {
Stack s;
For (int I=1; I & lt; Size; I++)
Supachai panitchpakdi ush (I);
cout <"The element of The stack are:";
For (int I=1; I & lt; Size; I++)
cout

return 0;
}

CodePudding user response:

Although p is not an array of class objects, need not add [], is correct, but we do not advocate to do so, because this is not the specification...
In general, need to release a class object or class object is assigned an array of memory, unified use delete [] way to release is very standard,
This kind of writing with brackets, can effectively avoid because of the reason caused by error or other hand may cause memory leaks, so write [] is a good habit, has become a standard answer,
  • Related