2015-11-25 112 views
0

我想动态分配堆上的数组使用具有指向数组和字符串的指针的结构。这是我的代码。如何动态分配一个二维数组结构

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

你应该修复复制+粘贴到StackOverflow上使代码更易于阅读时可能发生的压痕。还要注意['void main' **不是**有效的C++](http://www.stroustrup.com/bs_faq2.html#void-main) – Tas

+1

当''data'是'nullptr'时'。在到达结构之前,这将失败。哦,你有两个变量叫做'data'。也不会去工作。 –

+3

你是否被谴责为手动内存管理?因为这可能是一项家庭作业。但是,如果没有,只需使用[int]的vector的[std :: vector](或简单的'std :: vector '并且不要打扰 – user3159253

回答

0

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

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数组。相反,您需要分配一个带有行* cols元素的1D数组,并执行数学运算来将行和列转换为1D数组的索引,或者您需要分配一个指针数组,其中每个指针指向一个包含数据的数组。为了容纳指针数组,你需要一个指向指针的指针,所以你需要使examsptr成为一个int **。您需要分配循环中指针数组指向的数组。

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]; 
} 
+0

指针数组不是一个二维数组... – immibis

+0

@immibis:它不是一个数组数组,但它是实现二维数组的概念 –

+0

编辑了一下回答了一下,以避免模糊不清,我意识到一个指针数组是不一样的堆栈分配二维数组。 – jtedit