简体   繁体   English

使用动态内存分配

[英]Using Dynamic Memory Allocation

So I've been told to create an array that will accept 10 integers from the user, store it into an array, and sort these values using a pointer bubble sort in ascending order. 因此,有人告诉我创建一个数组,该数组将接受来自用户的10个整数,将其存储到数组中,并使用指针气泡升序对这些值进行排序。

I believe I have successfully done this much, but I am having trouble with the second part. 我相信我已经成功地做到了这一点,但是我在第二部分遇到了麻烦。

"Dynamically Allocate another array of 10 integers. Copy elements from the first into the second, but in reverse order (ie descending order). Display the elements of the first and second array in order and deallocate the dynamically allocated array." “动态分配另一个由10个整数组成的数组。将元素从第一个整数复制到第二个中,但顺序相反(即降序)。按顺序显示第一个和第二个数组的元素,并动态分配动态分配的数组。”

I am able to display the first array in order, and I know that to deallocate the array you must use the the delete function, but I am not so sure on how to construct the Dynamic Array. 我能够按顺序显示第一个数组,并且我知道要解除分配数组,必须使用delete函数,但是我不确定如何构造动态数组。

*I have not included the functions since I don't believe they are necessary for this part, but if I do, then I'll post them as well. *我没有包括这些功能,因为我认为它们对于这部分不是必需的,但是如果我这样做了,那么我也将其发布。

Thanks in advance for any suggestions and clarifications. 预先感谢您的任何建议和澄清。

#include <iostream>

using namespace std;

void sortArray(int * , int);
void showArray(const int * , int);
int binarySearch(const int *, int, int);

int main(void)
{
    int const MAX_NUM = 10;
    int numbers [MAX_NUM];
    int counter;
    int findval;
    int index;
    char again;

    cout<< "Please enter 10 integer values."<< endl;
    for(counter=0; counter< MAX_NUM ; counter++)
    {
        cout << "Enter a value for "<< counter+1 << ": ";
        cin >> *(numbers+counter);
    }


    sortArray(numbers, 10);

    cout << endl << "The values in ascending order are: " << endl;
    showArray(numbers, 10);

    do
    {
        cout<< endl <<  "Enter the value you are searching for: ";
        cin >> findval; 
        cout << endl;
        index = binarySearch(numbers , MAX_NUM , findval);
        // Display the results of the search.
        if (index == -1)
            cout << "Number was not found." << endl << endl;
        else
            cout << "Number "<< findval<<" found in position " << index + 1 << endl << endl;
        // Does the user want to do this again?
        do
        {
            cout << "Would you like to look up another number? (y/n) ";
            cin >> again;
        }
        while(again != 'y' && again != 'Y' && again != 'n' && again != 'N');
    } 
    while (again == 'Y' || again == 'y');

    cout<< endl << "Thank You. Press the return key to continue...";

    cin.get();
    cin.ignore();
    return 0;   
}

Dynamic memory management should be done using the C++ standard classes and concepts as available with either smart pointers or containers . 动态内存管理应使用C ++标准类和概念(通过智能指针容器可用)来完成。

Using C++ language correctly doesn't require you to use new / delete for most of the use cases you actually need to cover. 正确使用C ++语言并不需要您在实际需要涉及的大多数用例中使用new / delete

Operator new should be used to allocate memory. 应该使用运算符new来分配内存。 For dealloaction use delete . 对于脱售,请使用delete

Start from allocation the memory: 从分配内存开始:

    int * dynArr = NULL; // pointer to work with dynamic array
    dynArr = new int[MAX_NUM]; // allocation of memory

Then check that memory was allocated, like: 然后检查是否已分配内存,例如:

    if( dynArr != NULL )
    {
        // do something
    }
    else
    {
        // report about problem and do not use pointer
    }

And use function for copying elements, eg: 并使用函数复制元素,例如:

void reversCopy(const int * source, int * destination, int number)
// Function for copying numbers from one array (memory) to other 
// in the revers order (first element goes to the last position).
// source - pointer to array where numbers will be read
// destination - pointer to array where numbers will be written
// number - number of elements to be copyed
{ 
    for(int i = 0; i < number; i++)
    {
        destination[i] = source[number - 1 - i];
    }
}

Eventually, free dymanic memory with operator: 最终,带有运算符的自由动态记忆:

  delete[] dynArr;
  dynArr = NULL;

and do not use dynArr after that. 并且之后不要使用dynArr

To dynamically allocate array you need to build code like this: 要动态分配数组,您需要构建如下代码:

int *arr = new int[size];  // you have to remember to free memory when you won't need this array anymore - use delete[] achieve this

size variable don't have to be const and compiler don't need to know value of it during compilation. size变量不必是const,编译器也不需要在编译期间知道其值。 You can ask user to provide size :) Not to reverse your original table just assassin elements in reversed way: 您可以要求用户提供大小:)不要以相反的方式刺客元素来逆转原始表:

for (int i = 0; i < size; ++i)
{
    arr[i] = numbers[size - i - 1]; <-- '-1' to not read outside of orginal array (in C++ index starts with 0)
}

If you want to revers table without using new one you should visit: Reverse Contents in Array . 如果要在不使用新表的情况下反转表,则应访问: 在Array中反转目录 There are few methods to do this :) 有几种方法可以做到这一点:)

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

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