简体   繁体   English

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

[英]Is this the correct way to allocate and delete dynamic memory in C++?

I have an assignment for class, in which I need to create 3 functions to test with constant arguments. 我有一个班级分配,在其中需要创建3个函数以使用常量参数进行测试。 I am also supposed to create and delete dynamic memory. 我还应该创建和删除动态内存。 I have attached the exact directions from the assignment, just in case, as well as my code. 我附上了作业的确切指示,以防万一,还有我的代码。

I apologize if the code is messy. 如果代码混乱,我深表歉意。 I am a beginning programmer and new to the site, so I'm not exactly sure how to format everything perfectly. 我是一个初学者,也是该网站的新手,所以我不确定如何完美格式化所有内容。

Directions from assignment: 分配方向:

Write a C++ program that will test three functions described below that use pointers and dynamic memory allocation. 编写一个C ++程序,它将测试下面描述的使用指针和动态内存分配的三个功能。

  1. Expand: takes an int array and the array's size as parameters. Expand:将一个int数组和该数组的大小作为参数。 It should create a new array that is twice the size of the argument array. 它应该创建一个新数组,其大小是参数数组的两倍。 The function should copy the contents of the argument array to the new array, and initialize the unused elements of the new array with -1. 该函数应将参数数组的内容复制到新数组,并使用-1初始化新数组的未使用元素。 The function should return a pointer to the new array. 该函数应返回一个指向新数组的指针。

  2. concatenate: takes two int arrays and the arrays' sizes as parameters (that's 4 parameters). 串联:将两个int数组和数组的大小作为参数(即4个参数)。 It should create a new array big enough to store both arrays. 它应该创建一个足够大的新数组来存储两个数组。 Then it should copy the contents of the first array to the new array, and then copy the contents of the second array to the new array in the remaining elements, and return a pointer to the new array. 然后,它应该将第一个数组的内容复制到新数组,然后在剩余元素中将第二个数组的内容复制到新数组,并返回指向新数组的指针。

  3. subArray: It takes an int array, a start index and a length as arguments. subArray:它使用一个int数组,一个起始索引和一个长度作为参数。 It creates a new array that is a copy of the elements from the original array starting at the start index, and has length equal to the length argument. 它创建一个新数组,该数组是从起始索引处开始的原始数组中元素的副本,并且长度等于length参数。 For example, subArray(aa,5,4) would return a new array containing only the elements aa[5], aa[6], aa[7], and aa[8]. 例如,subArray(aa,5,4)将返回仅包含元素aa [5],aa [6],aa [7]和aa [8]的新数组。

My code: 我的代码:

#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;
}

Your set up is very good. 您的设置非常好。 Glad to see you're getting the hang of it. 很高兴看到您掌握了它。 Your functions could use some optimization, however. 但是,您的函数可以使用一些优化。 Before we begin, Id 'd like to note that C++ has a std::vector class which dynamically allocates memory as needed and supplies many powerful mod functions. 在开始之前,我想指出C ++有一个std::vector类,该类根据需要动态分配内存并提供许多强大的mod函数。 I'd recommend checking that out as it would take your program to the next level. 我建议您检查一下,因为这样会使您的程序更上一层楼。 To begin, Your Expand() function is pretty well set up. 首先,您的Expand()函数已经很好地设置了。 Just some minor modifications: to clean up your code, 只需进行一些小修改:清理代码,

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

can simply become: 可以简单地变成:

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

and within your for loop, there is no need to check the complete range of i , only its upper bound: 在您的for循环中,无需检查i的完整范围,只需检查其上限:

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

can become: 可以变成:

if (i < size) 

This will have the same result as your if-statement but is more elegant since i will never be less than 0. 这将具有与if-statement相同的结果,但是更加优雅,因为i永远不会小于0。

Moving on, your concatenate() function could become a lot simpler. 继续,您的concatenate()函数可能会变得简单得多。 While what you are doing is technically correct and works, your concatenate() function could simplify to: 虽然您所做的工作在技术上是正确的并且可以工作,但是您的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;

}

Furthermore, in your subArray() function, you can reduce: 此外,在subArray()函数中,您可以减少:

//Create new array size
int subSize = length;

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

to: 至:

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

Lastly, your main function could use an overhaul. 最后,您的主要功能可能需要大修。 Consider adding a writeArray() function since you are repeating that task often: 考虑添加一个writeArray()函数,因为您经常重复执行该任务:

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

That way your main() can become: 这样,您的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;

}

The rest of your program looks decent. 程序的其余部分看起来不错。 Keep up the good work! 保持良好的工作!

    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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM