在你阅读我的代码之前,我希望每个人都知道我没有在任何地方使用我的代码,这就是为什么它没有太多注释的原因。这只是我写的一个例子来问这个问题,它按照我想要的方式工作。随意尝试一下。
我对我的删除功能有疑问。是否删除[] pTemp->top3Grades;实际上删除/释放所有数组项?它知道在 3 个元素后停止吗?如何?如果内存中的某些数据可能与前 3 个数据相同(或相同类型的数据(,该怎么办?3 是否秘密传递到删除函数中,以便它知道何时停止?还是只是删除第一个元素pTemp->top3Grades[0]?
如果可能,我将如何检查它是否被删除?我使用XCode,如果它有帮助,它带有调试器。
#include <iostream>
using namespace std;
struct Students{
int idNum;
int age;
Students* pNext;
int* top3Grades;
};
void deleteAllStudents(Students* *head){
Students* pTemp = *head;
while (pTemp!=NULL) {
*head = pTemp->pNext;
delete[] pTemp->top3Grades; //Does this eliminate all 3 elments
//or just the first? How would you
//check if it is?
delete (pTemp); //Might as well ask...how I can see
//this was deleted/freed up?
pTemp=*head;
}
}
void addStudent(Students* *head, int id, int age, int grade1, int grade2, int grade3){
Students* studentEntry= new Students;
studentEntry->top3Grades= new int[3]; // Yes I could have set this as static when
// defining it in struct up above, but
// this way is related to my question later
studentEntry->top3Grades[0] = grade1;
studentEntry->top3Grades[1] = grade2;
studentEntry->top3Grades[2] = grade3;
studentEntry-> idNum = id;
studentEntry-> age = age;
studentEntry->pNext=NULL;
Students* pTemp;
pTemp = *head;
if (*head==NULL) {
*head = studentEntry;
} else{
while (pTemp->pNext!=NULL) {
pTemp= pTemp->pNext;
}
pTemp-> pNext= studentEntry;
}
}
void dispalyAllStudents(Students* *head){
Students* pTemp;
pTemp = *head;
while (pTemp!=NULL) {
cout<<"ID #: "<<pTemp->idNum<<" Age: "<<pTemp->age<<endl;
cout<<"Best grades are "
<<pTemp->top3Grades[0]<<" "
<<pTemp->top3Grades[1]<<" "
<<pTemp->top3Grades[2]
<<endl<<endl;
pTemp= pTemp->pNext;
}
}
int main()
{
int inputNum, studentID, studentAge, bestGrade1, bestGrade2, bestGrade3;
Students* pHead=NULL;
cout<< "How many records do you want to input? ";
cin >> inputNum;
for (int i = 0; i<inputNum; i++) {
cout<<endl;
cout<<"Enter ID Number: ";
cin>>studentID;
cout<<"Enter age: ";
cin>>studentAge;
cout<<"Enter first best grade: ";
cin>>bestGrade1;
cout<<"Enter second best grade: ";
cin>>bestGrade2;
cout<<"Enter third best grade: ";
cin>>bestGrade3;
addStudent(&pHead, studentID, studentAge, bestGrade1, bestGrade2, bestGrade3);
}
cout<< "--------"<<endl;
dispalyAllStudents(&pHead);
deleteAllStudents(&pHead);
return 0;
}
是的,如果你给它传递一个从 new[]
调用返回的指针,delete[]
知道有多少个元素。在您的代码中,您基本上具有:
int * p = new int[3];
// ...
delete [] p;
这正是它的设计目的。
它是如何做到的?那不是你的事。至于本例,在准标准的 Itanium ABI for C++中,没有什么可做的,你基本上最终会在底层内存上调用free()
。(因此,只需使用您对free()
的现有理解来填补空白。如果数组元素的类型不是普通的可破坏的,编译器将需要将数组元素的数量存储在某个"隐藏"位置(Itanium ABI 指定(的某个位置,以便它可以调用所有析构函数。