动态分配

Dynamically allocated

本文关键字:动态分配      更新时间:2023-10-16

我需要帮助,更改大小和arr,在主函数中动态分配内存(动态分配)

该程序在第一个程序中使用整数循环,而类和结构是第二个程序

程序_1

#include <iostream>
#include <iterator>
using namespace std;
void display_desc(const int arr[], int size)
{
int copy_arr[size];
copy(arr, arr + size, copy_arr);
int temp;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (copy_arr[i] > copy_arr[j]) {
temp = copy_arr[i];
copy_arr[i] = copy_arr[j];
copy_arr[j] = temp;
}
}
}
for (int i = 0; i < size; i++) {
cout << copy_arr[i] << " ";
}
cout << endl;
}
int main()
{
int size = 5;
int arr[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
display_desc(arr, size);
}

以及程序_2更改int main()中的变量以使用动态内存分配

#include <iostream>
#include <iterator>
#include <windows.h>
using namespace std;
const int SLOT_ROOM = 5;
class Person {
public:
Person()
{
name = "";
}
Person(string names)
{
name = names;
}
void set_name(string names) { name = names; }
string get_name() { return name; }
private:
string name;
};
struct Slot {
bool blank;
Person person;
};
class rental {
public:
Slot used[SLOT_ROOM];
rental()
{
for (int i = 0; i < SLOT_ROOM; i++) {
Person person;
used[i].person = person;
used[i].blank = true;
}
}
int in(const Person person)
{
for (int i = 0; i < SLOT_ROOM; i++) {
if (used[i].blank) {
used[i].blank = false;
used[i].person = person;
cout << "used in position " << i << endl;
return i;
}
}
cout << "the rental is full" << endl;
return -1;
}
bool out(int i)
{
used[i].blank = true;
}
Slot* get_rental_list()
{
return used;
}
void print_person_list()
{
cout << endl
<< "List rental" << endl;
for (int i = 0; i < SLOT_ROOM; i++) {
cout << "Slot rental to " << i << endl;
cout << "Name: " << used[i].person.get_name() << endl;
cout << "Avail: " << used[i].blank << endl
<< endl;
}
}
private:
int SLOT_ROOM = 2;
string time_rental;
};
int main()
{
rental rental;
Person person_1("make");
Person person_2("angel");
rental.in(person_1);
rental.in(person_2);
rental.print_person_list();
rental.out(2);
rental.print_person_list();
rental.in(person_2);
rental.print_person_list();
}

请帮忙,我不明白如何使用动态内存分配

我仍然在学习c++

更改

int arr[size];

int* arr = new int[size];

您需要对display_desc中的int copy_arr[size];进行相同的更改。

你还需要delete[]内存一旦你完成它

delete[] arr;

CCD_ 4在display_desc的末尾。

在第二个问题中,很难理解你想要什么。为什么要使用动态分配?你的代码看起来非常好。你也没有说你想使用动态分配的是哪个变量。