[英]Using Dynamic Memory Allocation
因此,有人告訴我創建一個數組,該數組將接受來自用戶的10個整數,將其存儲到數組中,並使用指針氣泡升序對這些值進行排序。
我相信我已經成功地做到了這一點,但是我在第二部分遇到了麻煩。
“動態分配另一個由10個整數組成的數組。將元素從第一個整數復制到第二個中,但順序相反(即降序)。按順序顯示第一個和第二個數組的元素,並動態分配動態分配的數組。”
我能夠按順序顯示第一個數組,並且我知道要解除分配數組,必須使用delete函數,但是我不確定如何構造動態數組。
*我沒有包括這些功能,因為我認為它們對於這部分不是必需的,但是如果我這樣做了,那么我也將其發布。
預先感謝您的任何建議和澄清。
#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;
}
應該使用運算符new
來分配內存。 對於脫售,請使用delete
。
從分配內存開始:
int * dynArr = NULL; // pointer to work with dynamic array
dynArr = new int[MAX_NUM]; // allocation of memory
然后檢查是否已分配內存,例如:
if( dynArr != NULL )
{
// do something
}
else
{
// report about problem and do not use pointer
}
並使用函數復制元素,例如:
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];
}
}
最終,帶有運算符的自由動態記憶:
delete[] dynArr;
dynArr = NULL;
並且之后不要使用dynArr
。
要動態分配數組,您需要構建如下代碼:
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變量不必是const,編譯器也不需要在編譯期間知道其值。 您可以要求用戶提供大小:)不要以相反的方式刺客元素來逆轉原始表:
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)
}
如果要在不使用新表的情況下反轉表,則應訪問: 在Array中反轉目錄 。 有幾種方法可以做到這一點:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.