简体   繁体   English

在C ++中用堆创建结构数组

[英]Creating an Array of Structures on the Heap in C++

I need to declare an array of structures on the heap, then transfer data from parallel arrays on the stack and from calculations into each structure. 我需要在堆上声明一个结构数组,然后从堆栈上的并行数组传输数据,并从计算传输到每个结构。 I declared 我宣布了

struct Grades
{
    string  studentName;
    int     scores[4];
    double  average;
};

....

Grades *art1301 = new Grades;

....

(art1301 + i)->studentName = names[i];

for((int i = 0 ; i < 5 ; i++ )
(art1301 + i)->scores[j] = exams[i][j];

(art1301 + i)->average = average; 

My program accesses the first record, but it crashes after it accesses the first field of the second record. 我的程序访问第一条记录,但在访问第二条记录的第一个字段后崩溃。 I don't understand why it works for the first record, but dies in the middle of the second? 我不明白为什么它适用于第一个记录,但在第二个记录中死了? Am I accessing the structure correctly? 我是否正确访问了结构?

Thank you. 谢谢。

To allocate an array, you need the array form of new , with the square brackets: 要分配数组,需要使用方括号的new数组形式:

Grades *art1301 = new Grades[200];
//                          ^^^^^

The array size can be a dynamically determined quantity. 阵列大小可以是动态确定的数量。

You aren't allocating memory for an array, you are allocating only for one element. 您没有为数组分配内存,只为一个元素分配。

As someone said in the comments, the key is in the new Grades instruction 正如有人在评论中所说,关键在于new Grades指令

In addition, unless you have another i variable declared before (which is a bad practice), that code doesn't compile because (art1301 + i)->studentName = names[i]; 另外,除非你之前声明了另一个i变量(这是一个不好的做法),否则该代码不能编译,因为(art1301 + i)->studentName = names[i]; will not find variable i 不会找到变量i

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

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