[英]How to create a pointer to pointer array to struct?
我想创建一个动态的指针数组,每个指针都指向一个结构体。 在程序中,有一个添加结构的选项,如果计数器最后到达数组的值,则数组会扩展。
struct student
{
string id;
string name;
};
int N=5;
int counter=0;
student **big=new student *[N]; //a ptr to an array of ptr's.
void add_student (int &counter,student **big)
{
int i;
if (counter==0)
{
for (i=0; i<N; i++)
{
big[i]=new student;
}
}
if (counter==N)
{
N+=5;
student **temp=new student *[N];
for (i=counter-1; i<N; i++)
{
temp[i]=new student;
}
for (i=0; i<counter; i++)
{
temp[i]=big[i];
}
delete [] big;
big=temp;
}
cout<<"Enter student ID: "<<endl;
cin>>(*big)[counter].id;
cout<<"Enter student name: "<<endl;
cin>>(*big)[counter].name;
counter++;
}
当我运行该程序时,尝试添加多个学生后崩溃。 谢谢!
试试这个代码。 主要问题是您在没有有效内存的情况下写入(*big)[counter].id
。 在下面的函数中,首先创建一个学生对象,然后将其写入。
PS:我尚未测试过代码,请告诉我它是否有问题。
struct student {
string id;
string name;
};
int N=5;
int counter=0;
student **big = new student *[N]; //a ptr to an array of ptr's.
// Variable big and counter is global, no need to pass as argument.
void add_student (student *new_student) {
// Resize if needed
if (counter==N) {
int i;
student **temp=new student *[N+5];
// Copy from the old array to the new
for (i=0; i<N; i++) {
temp[i]=big[i];
}
// Increase maximum size
N+=5;
// Delete the old
delete [] big;
big=temp;
}
// Add the new student
big[counter] = new_student;
counter++;
}
// Function called when we should read a student
void read_student() {
student *new_student = new student;
cout<<"Enter student ID: "<<endl;
cin>>new_student->id;
cout<<"Enter student name: "<<endl;
cin>>new_student->name;
// Call the add function
add_student (new_student);
}
我刚试过 该错误是因为您没有正确处理指向结构的指针。 将指针传递给指向某物的指针意味着该函数不仅可以更改其指向的东西,还可以更改指针地址。 因此在函数中声明一个指向指针的指针是可以的,但是将全局p声明为p到s并没有多大意义。 您可以使用&ptr达到相同的效果。 从p到p到s,即将指针的地址传递给函数。 我进行了一些更改,但不确定是否可行。 我将在4/5小时后再试一次,并将详细检查问题。 暂时请满足以下条件。 (可能是下面的一些错误,所以要小心)
struct student
{
string id;
string name;
};
int N=5;
int counter=0;
student *big=new student[N]; //a ptr to an array of ptr's.
void add_student (int &counter,student **ppBig)
{
int i;
if (counter==0)
{
for (i=0; i<N; i++)
*ppBig[i]=new student;
}
if (counter==N)
{
N+=5;
student *temp=new student [N];
for (i=counter-1; i<N; i++)
temp[i]=new student;
for (i=0; i<counter; i++)
temp[i]=*ppBig[i];
delete[] *ppBig;
ppBig=temp;
}
cout<<"Enter student ID: "<<endl;
cin>>(*big)[counter].id;
cout<<"Enter student name: "<<endl;
cin>>(*big)[counter].name;
counter++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.