我想创建一个动态指针数组,每个指针指向一个结构。在程序中有一个添加结构的选项,如果计数器到达数组的最后一个值,则数组会扩展。
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++;
}
当我运行该程序时,在我尝试添加多个学生后它崩溃了。谢谢!
答案 0 :(得分:0)
试试这段代码。主要问题是你写(*big)[counter].id
而没有这个有效的记忆。在下面的函数中,首先创建一个student对象,然后写入。
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);
}
答案 1 :(得分:0)
我刚试过。错误是因为您没有正确处理指向结构的指针。传递一个指向某事物的指针意味着该函数可以改变指针地址,而不仅仅是它指向的东西。所以在函数中声明一个指向指针的指针是可以的,但是声明p到p的全局p没有多大意义。使用&amp; 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++;
}