繁体   English   中英

将分配多少 memory 为 Arrays

[英]How much memory for Arrays will be allocated

我在 c++ 中编写了一段代码,我需要在其中创建 Arrays。

让我们假设数组的长度取决于一些可以变化的外部因素(例如: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
}

显然,我根据某些标准在三个地方创建了数组。

我想知道会分配多少 memory。 如果numberOfStudents非常小,比如 10,那么else if和 else 块中的其他 arrays 也会消耗 memory 吗? 在这种情况下,将 50 个 memory 块用于最小阵列,否则将导致 1000+200+50=1250 块 memory 使用。

我的编译器不符合 c99。所以,每当我尝试创建动态长度 arrays 时,我总是会遇到编译错误。

另外,我不能使用向量。 对于任何建议,您为什么不使用矢量,我会说谢谢。 但不幸的是,我不能使用它,因为 MISRA C 不允许这样做。

需要注意的是,我对 C++ 比较陌生。 曾是 Java 开发人员!

非常小,比如 10,那么 else if 和 else 块中的其他 arrays 也会消耗 memory 吗?

不,编译器会在进入块时分配堆栈空间,并在离开块时释放堆栈空间,所以:

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
}

从未进入的块不会对分配的堆栈空间量产生任何影响。

也就是说,如果您想正确支持任意数量的学生,最好使用std::vector<Student> ,或者如果不允许这样做,您可以改为使用堆分配(例如Student * students = new Student[numberOfStudents]; [...]; delete [] students; )。

暂无
暂无

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

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