In: Computer Science
4.2 Lab: new and delete
new is the operator used to dynamically allocate memory while the program is running
delete is the operator used to release memory when it is no longer needed, so it could be used next time new is used
This lab gives you an example of using new and delete with an array of structures.
Your tasks are listed below:
// Lab: new and delete
#include <iostream>
#include <string>
using namespace std;
struct Stu{
string name;
double gpa;
};
Stu *copyList(Stu list[], int n);
void printList(Stu *list, int n, string desc);
int main() {
Stu list[10] = {{"Tom", 3.5}, {"Bob", 2.9}, {"Ann", 3.2},
{"Dan", 3.1}, {"Zoe", 2.9}};
Stu *backup;
int n = 5;
printList(list, n, "Original");
backup = copyList(list, 5);
printList(list, n, "Backup");
// Release memory
delete [] backup;
return 0;
}
// This function dynamically allocates an array of n STU
structures,
// copies data from list to the new array, one element at a
time,
// and returns a pointer to the new array
Stu *copyList(Stu list[], int n)
{
Stu *backup;
/* write your code here */
return backup;
}
// This functions displays an array of structures
// Note: it doesn't matter if the array is
// statically allocated or dynamically allocated
void printList(Stu *anyList, int n, string desc)
{
cout << endl << desc << endl;
for (int i = 0; i < n; i++)
{
cout << anyList[i].name << " " << anyList[i].gpa
<< endl;
}
}
// please do not use any recursive functions or anything, this simply testing pointers
#include <iostream>
#include <string>
using namespace std;
struct Stu{
string name;
double gpa;
};
Stu *copyList(Stu list[], int n);
void printList(Stu *list, int n, string desc);
int main() {
Stu list[10] = {{"Tom", 3.5}, {"Bob", 2.9}, {"Ann", 3.2}, {"Dan",
3.1}, {"Zoe", 2.9}};
Stu *backup;
int n = 5;
printList(list, n, "Original");
backup = copyList(list, 5);
printList(backup, n, "Backup");
// Release memory
delete [] backup;
return 0;
}
// This function dynamically allocates an array of n STU
structures,
// copies data from list to the new array, one element at a
time,
// and returns a pointer to the new array
Stu *copyList(Stu list[], int n)
{
Stu *backup;
backup=new Stu[n];//allocate memory using new operator
for(int i=0;i<n;++i)
{
backup[i].name=list[i].name;
backup[i].gpa=list[i].gpa;
}
return backup;
}
// This functions displays an array of structures
// Note: it doesn't matter if the array is
// statically allocated or dynamically allocated
void printList(Stu *anyList, int n, string desc)
{
cout << endl << desc << endl;
for (int i = 0; i < n; i++)
{
cout << anyList[i].name << " " << anyList[i].gpa
<< endl;
}
}
Output