简体   繁体   中英

How much memory for Arrays will be allocated

I write a piece of code in c++ where I need to create Arrays.

Let us assume the length of array depends on some external factors(eg: numberOfStudents) which can vary.

my code follows


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
}

clearly I created array at three places depending on some criteria.

I want to know how much memory will be allocated. if numberOfStudents is very small, say 10, then will the other arrays in else if and else blocks also consume memory? in such a case will 50 blocks of memory be used for smallest array or will it result in 1000+200+50=1250 block of memory usage.

My compiler is NOT c99 compliant.So, whenever i try creating dynamic length arrays,which I always preferred, I get compilation errors.

Also, I cannot use Vectors. For any suggestion, that why don't you use vector, I will say thanks. But unfortunately I cannot use it as MISRA C does not allow the same.

To be noted, I am relatively new to C++. Was a Java developer!

is very small, say 10, then will the other arrays in else if and else blocks also consume memory?

No. The compiler will allocate stack space when entering a block, and deallocate stack space when leaving the block, so:

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
}

Blocks that are never entered will not have any effect on the amount of stack space allocated.

That said, if you want to properly support an arbitrary number of Students, you're probably better off using a std::vector<Student> , or if that's not allowed, you could fall back to heap-allocation instead (eg Student * students = new Student[numberOfStudents]; [...]; delete [] students; ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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