C++ 如何将二维数组动态分配给结构
我试图使用一个具有指向数组指针和字符串的结构在堆上动态分配数组。这是我的密码C++ 如何将二维数组动态分配给结构,c++,arrays,struct,C++,Arrays,Struct,我试图使用一个具有指向数组指针和字符串的结构在堆上动态分配数组。这是我的密码 struct StudentRecords { string names; int* examsptr; }; void main() { const int NG = 5; string names[] = { "Amy Adams", "Bob Barr", "Carla Carr", "Dan Dobbs", "
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数组,并进行数学运算以将row和col转换为1D数组的索引,或者需要分配一个指针数组,其中每个指针指向一个包含数据的数组。要保存指针数组,需要一个指向指针的指针,因此需要将examptr设置为int**
然后需要分配循环中指针数组指向的数组
例如:
//如果要取消引用,则不能为null ptr
StudentRecords*数据=新StudentRecords();
//数据->是(*数据)的简写。
//分配指针数组,长度为NG
数据->examsptr=新整数*[NG]
//现在做数组的第二维
对于(int i=0;iexamsptr[i]=新整数[NG];
}
您应该修复复制+粘贴到StackOverflow时可能出现的缩进,以使代码更易于阅读。还请注意,当数据为nullptr
时,您使用的是*数据。这将在您到达结构之前失败。哦,还有两个变量叫做data
。也不行。你是不是被迫要进行手动内存管理?因为这是你的家庭作业。如果没有,只需使用int
的vector
s(或者简单地使用std::vector
),不用麻烦了。为什么要让数组有5列,但每行只提供4个值?整个想法很糟糕;即使你不想使用容器类,你也应该只进行int检查[NG];
在每个StudentRecord
中,而不是使用pointer@immibis:它不是数组的数组,但它是实现2D数组概念的几种方法之一。对答案稍加编辑以避免歧义,我意识到指针数组与堆栈分配的2D数组不同。
//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];
}