c++ - 将为数组分配多少内存

标签 c++ arrays

我用 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/

相关文章:

c++ - 智能指针的 const 正确性

带有二维数组的 Java 程序

arrays - 上下文类型 'Emoji' 不能与数组文字一起使用

c - 如何显示字符数组?

C 数组与结构

c++ - 如何将模板参数限制为模板化接口(interface)特化的后代?

c++ - boost asio async_read_some 只读取数据片段

C++以不同方式读取两个输入文件

c++ - Openmp 和减少 std::vector?

javascript - 如何将 jquery 数组值发送到 codeigniter Controller