Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why allocate an array of size 1 more than the requested size?

Tags:

c++

This is really interesting because our instructor was teaching this to us yesterday and he couldn't figure it out himself. So, we're kinda left hanging on this without knowing the actual reason why.

Here is the array implementation of a Queue in a famous book (which I don't have, but that's what my instructor said. The author is very reputed):

class QUEUE {
private:
    int* q;
    int N;
    int head;
    int tail;
public:
    QUEUE(int maxN) {
        q = new int[maxN + 1];
        N = maxN + 1; head = N; tail = 0;
    }
    int empty() const {
        return head % N == tail;
    }
    void put(int item) {
        q[tail++] = item; tail = tail % N;
    }
    int get() {
        head = head % N; return q[head++];
    }
};

Inside the constructor, you see q = new int[maxN + 1];. But why the '+ 1' ? Why is he allocating one extra int block of memory?

like image 219
Kane Williamson Avatar asked Mar 27 '15 16:03

Kane Williamson


People also ask

Why is it necessary to give the size of an array in declaration?

We need to give the size of the array because the complier needs to allocate space in the memory which is not possible without knowing the size. Compiler determines the size required for an array with the help of the number of elements of an array and the size of the data type present in the array.

Why does the GROW Method double the size of the array instead of just increase it by one cell?

Doubling reduces the cost to linear time.

When declaring array its size should be a?

Declaring Arrays: The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable. The compiler uses the size to determine how much space to allocate (i.e. how many bytes).

What happens if try to access an element with an index greater than the size of the array in C?

If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.


1 Answers

The problem that adding one to maxN solves is that if you allocate exactly maxN items, you would not be able to distinguish these two situations:

  • The queue is empty, and
  • The queue has exactly maxN items.

In both these situations head and tail would be equal to each other modulo N.

Note: the implementation is not ideal, because inserting maxN+1-th element wraps the queue around, so it becomes empty again. This shortcoming can be addressed in three ways:

  • Throw an exception when queue overflows,
  • Change return type to bool, ignore insertions that overflow the queue, and return false if an insertion is ignored, or
  • Silently ignore insertions that overflow the queue (not recommended).
like image 56
Sergey Kalinichenko Avatar answered Oct 08 '22 20:10

Sergey Kalinichenko