如何创建指向指向结构的指针数组的指针

How to create a pointer to pointer array to struct?

本文关键字:指针 数组 结构 何创建 创建      更新时间:2023-10-16

我想创建一个指针的动态数组,每个指针都指向一个结构。在程序中有一个添加结构的选项,如果计数器达到数组值的最后一个,数组就会扩展。

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++;

}