繁体   English   中英

如何动态地将二维数组分配给结构

[英]How to dynamically allocate an 2d array to a struct

我正在尝试使用具有指向数组和字符串的指针的结构在堆上动态分配数组。 这是我的代码。

    struct StudentRecords
  {
     string names;
     int* examsptr;
  };


    void main()
  {


const int NG = 5;

string names[] =  { "Amy Adams", "Bob Barr", "Carla Carr",
                     "Dan Dobbs", "Elena Evans"
                   };

int exams[][NG] = 
{ 
    { 98,87,93,88 },
    { 78,86,82,91 },
    { 66,71,85,94 },
    { 72,63,77,69 },
    { 91,83,76,60 }
};

StudentRecords *data = nullptr;
(*data).examsptr = new int[][NG];

int *data = new int[NG*NG];

您当前的代码存在很多问题。

StudentRecords *data = nullptr; //here you set data to nullptr
(*data).examsptr = new int[][NG]; //then you dereference nullptr, BAD

int *data = new int[NG*NG]; //then you declare another variable with the same name, BAD

您应该重命名您的变量之一,并将学生记录设置为StudentRecords的实际实例。

您无法像“ new int [rows [cols]””那样一步一步动态分配2D数组。 取而代之的是,您需要分配一个具有rows * cols元素的1D数组,并进行数学运算以将行和col转换为1D数组的索引,或者您需要分配一个指针数组,其中每个指针都指向一个保存数据的数组。 要保存指针数组,您需要一个指向指针的指针,因此需要将examsptr设置为int **。

然后,您需要分配循环中的指针数组所指向的数组。

例如:

//cant be nullptr if you want to dereference it
StudentRecords *data = new StudentRecords(); 

//data-> is shorthand for (*data).
//allocates array of pointers, length NG
data->examsptr = new int*[NG]

//now make the 2nd dimension of arrays
for(int i = 0; i < NG; ++i){
    data->examsptr[i] = new int[NG];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM