c++ - 如何创建一个指向指针数组的指针来构造?

标签 c++ arrays pointers struct delete-operator

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

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);
}

关于c++ - 如何创建一个指向指针数组的指针来构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19384243/

相关文章:

c++ - QTextEdit 作为 HTML 编辑器

c++ - IFileOperation 和进度对话框

android - 当我们实例化 Caffe2 预测器时,应用程序卡住了

c++ - 如何获取DLL的文件名?

c - 字符串指针的子字符串指针

c - 错误 : A label can only be part of a statement

JavaScript 数组没有正确索引?

c - C 中的动态 3D 可变列字符数组操作

java - 使用for循环来搜索数组

C 编程指针和字符串操作