在c ++中创建节点时,何时需要使用new
运算符来确保内存可用于分配。
例如,当声明用于查找现有链表的末尾的节点指针NewNode以便将节点添加到列表末尾时,此函数不使用typedef Node* NodePtr; /*a type definition for NodePtr for ease of use in `the larger program this function is a part of*/`
void AddNode(char NewChar, NodePtr List)
{
NodePtr NewNode = List; //make NewNode point to List
while (NewNode->Link != NULL) //find end of linked list
NewNode = NewNode->Link;
NewNode->Link = new (nothrow) Node; //create a new Node at the end of the list
if (NewNode->Link == NULL) //make sure Node was created
return;
NewNode = NewNode->Link; //make NewNode point to the Node just created
NewNode->Ch = NewChar; //fill Ch part of NewNode
NewNode->Link = NULL; //make sure the list ends with NULL
}
void TestAddNode(NodePtr List)
{
char NewChar;
cout << "\n\n---------------- Testing AddNode -------------------\n\n";
cout << "Character to be added? ";
NewChar = cin.get();
cin.ignore();
if (NewChar == '\n') // User pressed just enter key.
{
cout << "Aborting AddNode...";
return;
}
cout << NewChar;
cout << " -- Adding \'" << NewChar << "\'";
AddNode(NewChar, List);
cout << "\n\nThe new list: ";
ShowList(List); //show list is another function that outputs the list
}
,但它确实使用`include "PARALLEL_ADDER.v"
module subtract(a,b,ans) ;
input [3:0] a,b ;
output [4:0] ans ;
wire carry ;
reg [3:0] temp ;
integer i ;
initial begin
for(i=0;i<=3;i=i+1)
temp[i] = 1 - b[i] ;
end
Parallel_adder P1(ans,carry,4'b0001,temp) ;
endmodule
实际将节点添加到列表末尾时{1}}。这是因为节点指针被用作非动态内存分配,指向已动态分配的其他内存或其他原因?在NewNode声明前面使用new(nothrow)是不正确的语法或逻辑?
{{1}}
答案 0 :(得分:2)
仅在动态分配新内存以存储新节点时才使用new
。在您的情况下,NewNode
只是指向List
指向的现有内存,因此这不是使用new
运算符的正确位置。