search

Home  >  Q&A  >  body text

C++ 中被delete后的指针还可以被赋值为NULL或者其他的指针变量吗?

在《剑指offer》的一书提供的源代码中看到这样的代码片段

unsigned int Sum_Solution1(unsigned int n)
{
    Temp::Reset();

    Temp *a = new Temp[n];
    delete []a;
    a = NULL;

    return Temp::GetSum();
}

其中 指针 a 被delete后又有 a = NULL,我试着在codeblocks上写了一下

但是在VS2013中就报错

能请大家帮忙给看看吗

大家讲道理大家讲道理2804 days ago576

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:47:37

    delete and new appear in pairs, and the error is caused by delete and has nothing to do with assigning values ​​to pointers.
    You set it before

    char *a = "test1";
    
    

    The a here is a pointer to the constant area and cannot be deleted.
    The example in the original code is the array usage of new and delete, so the exception in Visual Studio is correct.
    If the deleted object is not new, the resulting behavior is undefined, so CodeBlocks does not report an error.

    reply
    0
  • Cancelreply