【问题标题】:C++ - New and Delete with ArraysC++ - 使用数组新建和删除
【发布时间】:2016-11-12 02:40:15
【问题描述】:

我正在尝试纠正内存泄漏,但无法弄清楚删除数组 [] 不起作用的原因。我尝试搜索其他帖子,但我被卡住了,所以我希望我能指出正确的方向。

我正在尝试重新分配内存,但是当我使用删除数组 [] 时,我一直在破坏代码。

以下是输出的示例以及我想要实现的目标: enter image description here

代码如下:

int main()
{
    cout << endl << endl;
    int* nArray = new int[arraySize];
    cout << "After creating and allocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
    for (int i = 0; i < arraySize; i++)
    {
        nArray[i] = i*i;
    }
    cout << "After initializing nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
    for (int i = 0; i < arraySize; i++)
    {
        cout << "  nArray[" << i << "] = " << nArray[i] << " at address <" << nArray+i << ">" << endl;
    }
    cout << endl << "Before reallocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
    nArray = new int[arraySize + 2];
    cout << dec << "After reallocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
    for (int i = 0; i < arraySize+2; i++)
    {
        nArray[i] = i*i;
    }
    return 0;
}

【问题讨论】:

  • 您可能已经探索过这个选项,但我想检查一下,为什么不使用 std::vector 来完成上面的操作?
  • 您给我们看的代码中没有delete

标签: c++ arrays memory


【解决方案1】:

您应该创建一个指向更大内存块的新指针。所以有一个新的指针nArray2 = new int[arraySize + 2]; 发生,但保留旧的nArray。现在,将 nArray 的内容复制到新指针。复制后可以delete[] nArray。但是现在你必须使用你的新指针,或者设置nArray 指向这个新数组。

【讨论】:

    【解决方案2】:

    您的问题的可能解决方案:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int arraySize=10;
    
        int* nArray = new int[arraySize];
    
        //init array
        for (int i = 0; i < arraySize; i++)
        {
            nArray[i] = i*i;
        }
    
        //simple realocation    
        //create bigger array
        int newArraySize = arraySize + 2;
        int* newNArray = new int[newArraySize];
    
        //copy old array to now one (truncate if smaler)
        for (int i = 0; i < (arraySize<newArraySize?arraySize:newArraySize); i++)
        {
            newNArray[i] = nArray[i];
        }
    
        //init new elements
        for (int i = arraySize; i < newArraySize; i++)
        {
            newNArray[i] = i*i;
        }
    
        //delete old array
        delete [] nArray;
    
        //set pointer to new array
        nArray = newNArray;
        //set new size for array
        arraySize = newArraySize;
    
        return 0;
    }
    

    cpp.sh/96bi

    【讨论】:

      猜你喜欢
      • 2015-04-04
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多