new 必须用于创建结构?
new must be used for creating struct?
我正在用 leetcode 写代码。对于Two add numbers的问题,我的解决方案无法被接受,因为我在创建struct时没有使用new。这是我的代码:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
struct ListNode temp(-1);
struct ListNode *pre = &temp;
bool PlusOne = false;
int val1 = 0;
int val2 = 0;
int sum;
while (NULL != l1 || NULL != l2)
{
if (NULL != l1)
{
val1 = l1->val;
l1 = l1->next;
}
if (NULL != l2)
{
val2 = l2->val;
l2 = l2->next;
}
if (PlusOne == true)
{
sum = (val1 + val2 + 1) % 10;
PlusOne = (val1 + val2 + 1) / 10;
}
else
{
sum = (val1 + val2) % 10;
PlusOne = (val1 + val2) / 10;
}
struct ListNode newNode(sum);
pre->next = &newNode;
pre = &newNode;
val1 = 0;
val2 = 0;
}
if (true == PlusOne)
{
struct ListNode newNode(1);
pre->next = &newNode;
}
pre = temp.next;
return pre;}
它说运行时错误,但如果我使用 pre->next = new ListNode(1) 替换
struct ListNode newNode(1);
pre->next = &newNode;
有没有人知道为什么?
It said runtime error, but it works if I use pre->next = new ListNode(1) replacing of struct ListNode newNode(1); pre->next = &newNode;
那是因为您指向一个局部变量,当 if
块存在时,该变量将被销毁。
if (true == PlusOne)
{
struct ListNode newNode(1);
pre->next = &newNode;
}
当控件从 if
块中出来时,pre->next
将指向未分配的内存。这类似于这样做
int* get_int() {
int a = 1;
return &a;
}
void process_int() {
int *p = get_int();
// oops! p is pointing to unallocated memory; undefined behaviour ensues
*p;
}
永远不要指向一个不会超过你的指针的局部变量。
new
工作的原因是您在自由存储中手动分配内存,该内存将一直存在,直到 delete
被调用或程序存在(以较早者为准)。
我正在用 leetcode 写代码。对于Two add numbers的问题,我的解决方案无法被接受,因为我在创建struct时没有使用new。这是我的代码:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
struct ListNode temp(-1);
struct ListNode *pre = &temp;
bool PlusOne = false;
int val1 = 0;
int val2 = 0;
int sum;
while (NULL != l1 || NULL != l2)
{
if (NULL != l1)
{
val1 = l1->val;
l1 = l1->next;
}
if (NULL != l2)
{
val2 = l2->val;
l2 = l2->next;
}
if (PlusOne == true)
{
sum = (val1 + val2 + 1) % 10;
PlusOne = (val1 + val2 + 1) / 10;
}
else
{
sum = (val1 + val2) % 10;
PlusOne = (val1 + val2) / 10;
}
struct ListNode newNode(sum);
pre->next = &newNode;
pre = &newNode;
val1 = 0;
val2 = 0;
}
if (true == PlusOne)
{
struct ListNode newNode(1);
pre->next = &newNode;
}
pre = temp.next;
return pre;}
它说运行时错误,但如果我使用 pre->next = new ListNode(1) 替换 struct ListNode newNode(1); pre->next = &newNode;
有没有人知道为什么?
It said runtime error, but it works if I use pre->next = new ListNode(1) replacing of struct ListNode newNode(1); pre->next = &newNode;
那是因为您指向一个局部变量,当 if
块存在时,该变量将被销毁。
if (true == PlusOne)
{
struct ListNode newNode(1);
pre->next = &newNode;
}
当控件从 if
块中出来时,pre->next
将指向未分配的内存。这类似于这样做
int* get_int() {
int a = 1;
return &a;
}
void process_int() {
int *p = get_int();
// oops! p is pointing to unallocated memory; undefined behaviour ensues
*p;
}
永远不要指向一个不会超过你的指针的局部变量。
new
工作的原因是您在自由存储中手动分配内存,该内存将一直存在,直到 delete
被调用或程序存在(以较早者为准)。