c++ - new 必须用于创建结构?

标签 c++ 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 block 存在时,该变量将被销毁。

if (true == PlusOne)
{
    struct ListNode newNode(1);
    pre->next = &newNode;
}

pre->next 将在控件从 if block 中出来时指向未分配的内存。类似于这样做

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 或程序存在(以较早者为准)之前,该内存将一直存在.

关于c++ - new 必须用于创建结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27763566/

相关文章:

c++ - UML 对描述模板化代码有用吗?

c++ - SDL 窗口在启动时关闭并返回 0

c++ - 设置变量的最大可能值 C++

C 预处理器计算最大 sizeof 结构

c++ - 如何在C++结构初始化中获取成员

c++ - 读入一个文件并将其分成 100 个较小的文件非常慢

c++ - QT C++ - 信号和槽 : "No such slot QLabel..." even the SLOT function is existing in my class

c - 优先队列数组(c)

c - 代表一个指针

c# - 数组和列表与结构的差异