这是在C ++中分配和删除动态内存的正确方法吗?

时间:2018-04-10 01:23:44

标签: c++ dynamic-memory-allocation

我有一个类的赋值,我需要创建3个函数来使用常量参数进行测试。我也应该创建和删除动态内存。我已附上作业的确切说明,以防万一,以及我的代码。

如果代码很乱,我很抱歉。我是一名初级程序员,也是网站的新手,所以我不确定如何完美地格式化所有内容。

转让指示:

  

编写一个C ++程序,它将测试下面描述的三个使用指针和动态内存分配的函数。

     
      
  1. 展开:获取一个int数组,并将数组的大小作为参数。它应该创建一个两倍于参数数组大小的新数组。该函数应将参数数组的内容复制到新数组,并使用-1初始化新数组的未使用元素。该函数应返回指向新数组的指针。

  2.   
  3. concatenate:将两个int数组和数组的大小作为参数(即4个参数)。它应该创建一个足以存储两个数组的新数组。然后它应该将第一个数组的内容复制到新数组,然后将第二个数组的内容复制到其余元素中的新数组,并返回指向新数组的指针。

  4.   
  5. subArray:它以一个int数组,一个起始索引和一个长度作为参数。它创建一个新数组,它是从起始索引开始的原始数组中元素的副本,其长度等于length参数。例如,subArray(aa,5,4)将返回一个只包含元素aa [5],aa [6],aa [7]和aa [8]的新数组。

  6.   

我的代码:

#include <iostream>

using namespace std;

int* Expand(int [], int);

int* concatenate(int[], int, int[], int);

int* subArray(int[], int, int);

int main()
{
    //Declare variables
    const int SIZEAA = 10;
    const int SIZEBB = 5;
    int aa[SIZEAA] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    int bb[SIZEBB] = { 11, 22, 33, 44, 55 };

    //Output both original arrays
    cout << "aa[10]: ";
    for (int i = 0; i < SIZEAA; i++)
        cout << aa[i] << " ";
    cout << endl;

    cout << "bb[5]: ";
    for (int i = 0; i < SIZEBB; i++)
        cout << bb[i] << " ";
    cout << endl;

    //Call the Expand function
    int* aaExpand = Expand(aa, SIZEAA);

    //Output expanded array
    cout << "Testing Expand: ";
    for (int i = 0; i < 20; i++)
        cout << aaExpand[i] << " ";
    //Release dynamic memory
    delete[] aaExpand;
    aaExpand = nullptr;
    cout << endl;

    //Call the concatenate function
    int* concatenateArray = concatenate(aa, SIZEAA, bb, SIZEBB);

    //Output concatenated array
    cout << "Testing concatenate: ";
    for (int i = 0; i < (SIZEAA + SIZEBB); i++)
        cout << concatenateArray[i] << " ";
    //Release dynamic memory
    delete[] concatenateArray;
    concatenateArray = nullptr;
    cout << endl;

    //Call subArray function
    int* arraySub = subArray(aa, 5, 4);

    //Output the sub array
    cout << "Testing subArray: ";
    for (int i = 0; i < 4; i++)
        cout << arraySub[i] << " ";
    //Release dynamic memory
    delete[] arraySub;
    arraySub = nullptr;
    cout << endl;
}

int* Expand(int aa[], int size)     /*This function takes in an array and 
the size as parameters, creates a new array of double the size, and copies 
the old array into it.It then adds -1 into all new spaces created. 
It returns a pointer to the new array*/
{
    //Declare new array
    int* aaNew;
    int newSize = size * 2;
    aaNew = new int[newSize];

    //Copy old array into new array
    for (int i = 0; i < newSize; i++)
    {
        if (i >= 0 && i < size)     //Check to see if it needs to copy an old value in or put -1 into the array
            aaNew[i] = aa[i];
        else
            aaNew[i] = -1;
    }

    return aaNew;
}

int * concatenate(int aa[], int sizeAA, int bb[], int sizeBB)   /*This 
function takes in two different arrays, creates a new array, then copies 
both arrays into the new array.It returns a pointer to the new array*/
{
    //Create new array size
    int newSize = (sizeAA + sizeBB);

    //Create new array
    int* concatArray;
    concatArray = new int[newSize];

    //Add elements of first and second array into new array
    for (int i = 0; i < newSize; i++)
    {
        if (i >= 0 && i < sizeAA)       //Check to see if a value from the first or second array is supposed to be added
            concatArray[i] = aa[i];
        else
            concatArray[i] = bb[i - sizeAA];
    }

    return concatArray;
}

int * subArray(int a[], int start, int length)    /* This function takes in 
an array, a start value, and a length value. It creates a new array and 
copies the values of the original array starting at the passed start value 
and continues until the new array is the length of the passed length value. 
It returns a pointer to the new array*/
{
    //Create new array size
    int subSize = length;

    //Create a new array
    int* sub;
    sub = new int[subSize];

    //Add elements of original array starting at the passed start value into new 
    array until the new array is the length specified by the argument
    for (int i = 0; i < subSize; i++)
    {
        sub[i] = a[start];
        start += 1;
    }

    return sub;
}

2 个答案:

答案 0 :(得分:1)

你的设置非常好。很高兴看到你了解它。但是,您的函数可以使用一些优化。在开始之前,我们要注意C ++有一个std::vector类,它根据需要动态分配内存并提供许多强大的mod函数。我建议您检查一下,因为它会将您的程序提升到一个新的水平。 首先,您的Expand()功能设置得非常好。只需进行一些小修改:清理代码,

int* aaNew;
int newSize = size * 2;
aaNew = new int[newSize];

可以简单地成为:

int newSize = size * 2;
int *aaNew = new int[newSize];

并且在for循环中,无需检查i的完整范围,只检查其上限:

if (i >= 0 && i < size) 

可以成为:

if (i < size) 

这与if-statement的结果相同,但更优雅,因为i永远不会少于0。

继续,您的concatenate()功能可以变得更加简单。虽然您所做的工作在技术上是正确且有效的,但您的concatenate()功能可以简化为:

int * concatenate(int aa[], int sizeAA, int bb[], int sizeBB) {

    int * result = new int[sizeAA + sizeBB];
    copy(aa, aa + sizeAA, result);
    copy(bb, bb + sizeBB, result + sizeAA);
    return result;

}

此外,在subArray()功能中,您可以减少:

//Create new array size
int subSize = length;

//Create a new array
int* sub;
sub = new int[subSize];

为:

//Create new array size
int subSize = length;
int *sub = new int[subSize];

最后,您的主要功能可以使用大修。考虑添加writeArray()函数,因为您经常重复该任务:

string writeArray(int ar[], int arLength) {
    string ret = "";
    for (int i = 0; i < arLength; i++)
        ret += " " + to_string(i);
    return ret + "\n";
}

这样main()可以成为:

int main() {

    //Declare variables
    const int SIZEAA = 10, SIZEBB = 5;
    int aa[SIZEAA] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    int bb[SIZEBB] = { 11, 22, 33, 44, 55 };

    //Output both original arrays
    cout << "aa[10]: " << writeArray(aa, SIZEAA);
    cout << "bb[5]: " << writeArray(bb, SIZEBB);

    //Call the Expand function
    int *aaExpand = Expand(aa, SIZEAA);
    cout << "Testing Expand: " << writeArray(aaExpand, SIZEAA * 2);

    //Call the concatenate function
    int *concatenateArray = concatenate(aa, SIZEAA, bb, SIZEBB);
    cout << "Testing concatenate: " << writeArray(concatenateArray,
                                                 (SIZEAA + SIZEBB));

    //Call subArray function
    int *arraySub = subArray(aa, 5, 4);
    cout << "Testing subArray: " << writeArray(arraySub, 4);
    //Output the sub array

    //Release dynamic memory
    delete[] aaExpand;
    delete[] concatenateArray;
    delete[] arraySub;

    aaExpand = nullptr;
    concatenateArray = nullptr;
    arraySub = nullptr;

}

你的程序的其余部分看起来不错。保持良好的工作!

答案 1 :(得分:-1)

    int* Expand(int elements[], int size)
    {
        int* new_elements = new int[2 * size];

        for (int i = 0; i < size; i++)
        {
            new_elements[i] = elements[i];
            new_elements[i + size] = -1;
        }

        return new_elements;
    }

    int* concatenate(int first[], int firstSize, int second[], int secondSize)
    {
        int* elements = new int[firstSize + secondSize];

        for (int i = 0; i < firstSize; i++)
        {
            elements[i] = first[i];
        }
        for (int j = 0; i < secondSize; j++)
        {
            elements[firstSize + j] = second[j];
        }

        return elements;
    }

    int* subArray(int elements[], int offset, int size)
    {
        int* new_elements = new int[size];

        for (int i = 0; i < size; i++)
        {
            new_elements[i] = elements[offset + i];
        }

        return new_elements;
    }