Search code examples
c++arraysmemorysizeallocation

How do I allocate size for a dynamic array in c++?


So I wrote a method in c++ where I remove a range of elements in an array. The thing is this is a dynamic array and the size of the array must always be a certain size. So if I remove alot of elements from the array and leave at least 5 empty spaces then I need to remove those 5 empty spaces. I already wrote a similar method where I remove one element. This is the line that checks to see if there's too much space:

if (size - 1 == allocated_size - BLOCK_SIZE){

Where size is the number of elements in the array, allocated_size is how much space is in the array and BLOCK_SIZE is 5. So with my other remove method, I need to do a similar check however what if I have an array of 15 elements and I remove 10 elements. Then I would have to remove 10 spaces in the array but I'm not sure how to do that. Here's what I have right now:

if (size - range <= allocated_size - BLOCK_SIZE){
            try {
                new_array = new int[allocated_size - BLOCK_SIZE];
            } catch (bad_alloc){
                throw exception (MEMORY_EXCEPTION);
            }

Where range is the number of elements I'm removing. My theory is that maybe I could make another variable and when I declare the array I say allocated_size - BLOCK_SIZE * n so if I need to remove 10 spaces then n would be 2. The problem I'm having trouble implementing that.


Solution

  • Could you use some int arithmetic,

    the number of empty slots in your array will be:

    int empty_slots = allocated_size - size;  
    

    The number of empty blocks will be:

    int empty_blocks = empty_slots / 5; 
    

    integer division truncates so for 0 - 4 empty slots you will have 0 empty blocks for 5-9 empty slots you will have 1 empty block etc...

    But don't you really want to know how big to make your new array? wouldn't that always be size, so:

    int blocks_need = size / 5;                // truncates 
    if (size % 5 > 0) {
        blocks_need = blocks_needed + 1;   // add a block if needed
    }   
    new_array = new int[blocks_needed * 5]; 
    

    or size + extra capacity if you want some extra capacity in your array.