我用 C++ 编写了一段代码,我需要在其中创建数组。
让我们假设数组的长度取决于一些可以变化的外部因素(例如:numberOfStudents)。
我的代码如下
typedef struct Student{
//some attributes
}Student;
if(numberOfStudents < 50)
{
Student students[50];
//some more code manipulating the array
}
else if(numberOfStudents > 50 && numberOfStudents < 200)
{
Student students[200];
//some more code manipulating the array
}
else
{
Student students[1000];//assuming there cannot be more than 1000 students
//some more code manipulating the array
}
显然,我根据某些标准在三个地方创建了数组。
我想知道将分配多少内存。如果
numberOfStudents
非常小,比如 10,那么 else if
中的其他数组否则 block 也会消耗内存?在这种情况下,最小数组将使用 50 个内存块,或者会导致 1000+200+50=1250 个内存块使用。
我的编译器不兼容 c99。所以,每当我尝试创建我一直喜欢的动态长度数组时,都会出现编译错误。
另外,我不能使用 vector 。对于任何建议,您为什么不使用 vector ,我会说谢谢。但不幸的是,我不能使用它,因为 MISRA C 不允许这样做。
需要注意的是,我对 C++ 比较陌生。曾是一名 Java 开发人员!
最佳答案
is very small, say 10, then will the other arrays in else if and else blocks also consume memory?
不,编译器会在进入 block 时分配堆栈空间,并在离开 block 时释放堆栈空间,所以:
if(numberOfStudents < 50)
{
// 50*sizeof(Student) bytes of stack space allocated at this point
Student students[50];
[... code executes here...]
// 50*sizeof(Student) bytes of stack space deallocated at this point
}
else if(numberOfStudents > 50 && numberOfStudents < 200)
{
// 200*sizeof(Student) bytes of stack space allocated at this point
Student students[200];
[... code executes here...]
// 200*sizeof(Student) bytes of stack space deallocated at this point
}
else
{
// 1000*sizeof(Student) bytes of stack space allocated at this point
Student students[1000];//assuming there cannot be more than 1000 students.
[... code executes here...]
// 1000*sizeof(Student) bytes of stack space allocated at this point
}
从未进入的 block 不会对分配的堆栈空间量产生任何影响。
也就是说,如果您想正确支持任意数量的学生,您最好使用
std::vector<Student>
。 ,或者如果不允许这样做,您可以改为使用堆分配(例如 Student * students = new Student[numberOfStudents]; [...]; delete [] students;
)。
关于c++ - 将为数组分配多少内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61530239/