简体   繁体   中英

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.

You can't dynamically allocate a 2D array in one step like 'new int[rows][cols]'. 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. To hold the array of pointers you need a pointer to a pointer, so you need to make examsptr an 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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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