简体   繁体   English

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

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

I'm trying to dynamically allocate an array on the heap using a structure that has a pointer to an array and a string. 我正在尝试使用具有指向数组和字符串的指针的结构在堆上动态分配数组。 Here's my code. 这是我的代码。

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

There's a number of problems with your current code. 您当前的代码存在很多问题。

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

You should rename one of your variables and set student records to an actual instance of StudentRecords. 您应该重命名您的变量之一,并将学生记录设置为StudentRecords的实际实例。

You can't dynamically allocate a 2D array in one step like 'new int[rows][cols]'. 您无法像“ new int [rows [cols]””那样一步一步动态分配2D数组。 Instead you either need to allocate a 1D array with rows*cols elements and do maths to convert a row and col into an index of the 1D array or you need to allocate an array of pointers, where each pointer points to an array holding the data. 取而代之的是,您需要分配一个具有rows * cols元素的1D数组,并进行数学运算以将行和col转换为1D数组的索引,或者您需要分配一个指针数组,其中每个指针都指向一个保存数据的数组。 To hold the array of pointers you need a pointer to a pointer, so you need to make examsptr an int**. 要保存指针数组,您需要一个指向指针的指针,因此需要将examsptr设置为int **。

You then need to allocate the arrays that are pointed at by the array of pointers in a loop. 然后,您需要分配循环中的指针数组所指向的数组。

EG: 例如:

//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