如何更改指针以使其指向其他位置?

时间:2017-10-20 09:30:07

标签: c++ pointers memory-management heap

我有这个c ++代码,我的想法是:

  1. 使用int 3(list = {3})创建一个列表。
  2. 创建一个名为temp的临时列表,并将'list'的元素转移到'temp',以便temp = {3,}。
  3. 将int 4添加到temp(temp = {3,4})。
  4. 删除'list'的内容。
  5. 更改首先指向“list”的指针,使其现在指向“temp”。
  6. 删除指向'temp'的指针,以便'list'是唯一的指针。

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int* list = new int[1];    // create 'list' which contains int 3.
        list[0] = 3;
    
        int* temp = new int[2];    // create 'temp' which is 1 element bigger than 'list'.
        for (int i = 0; i < 1; i++) {    // carry over the elements of 'list' to 'temp'.
            temp[i] = list[i];    
        }
    
        temp[1] = 4;    // add extra element to 'temp'
        delete[] list;    // delete contents of 'list'.
        list = temp;    // let 'list' point to 'temp'. 
    
        // How to delete pointer that points to 'temp' so that 'list' is the only pointer?
    
        return 0;
    }
    

    提前谢谢。

1 个答案:

答案 0 :(得分:0)

正如其他人提到的那样,没有必要删除指针,就像不需要删除int一样,只要你不再需要它就可以忽略它。

但是你仍然可以使用范围摆脱它:

    #include <iostream>

    using namespace std;

    int main()
    {
        int* list = new int[1];    // create 'list' which contains int 3.
        list[0] = 3;

        //Open new scope.
        {

            int* temp = new int[2];    // create 'temp' which is 1 element bigger than 'list'.
            for (int i = 0; i < 1; i++) {    // carry over the elements of 'list' to 'temp'.
                temp[i] = list[i];    
            }

            temp[1] = 4;    // add extra element to 'temp'
            delete[] list;    // delete contents of 'list'.
            list = temp;    // let 'list' point to 'temp'. 

        // Close the scope. tmp does not exist anymore after this. Trying to use temp after this point will result in a compilation error.
        }

        //does not work anymore:
        //temp = nullptr;

        return 0;
    }