2

Im reading up for a exam in C++ and just fideling around in order to get a better sense of the language. My understanding is that arrays in c++ are defined with a fixed length either before run time or dynamically. Knowing this I don't understand why C++ accepts this. I wouldn't think that it would be possible to add element to an array of length 0;

int * TestArray = new int[0];
TestArray[0]=10;
TestArray[1]=20;
TestArray[2]=30;
ikop
  • 1,760
  • 1
  • 12
  • 24

3 Answers3

4

Writing to array elements outside of the valid size is Undefined Behaviour. It's a bug and your program is ill formed. But the compiler is not required to issue a diagnostic (although most will with the right warning options). It's your responsibility to follow the rules.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
1

You may not access any elements in a zero sized array. It results in undefined runtime behavior. However, zero sized arrays are allowed for various reasons.

First, it allows you to make functions less complicated by skipping size checks:

   void f(size_t n)
   {
    int * ptr = new int[n];
    //...
    delete[] ptr;
   }

instead of:

void f(size_t n)
{
 if (n>0)
 {
  int * ptr = new int[n];
  //...
  delete[] ptr;
 }
}

Second, the intent was to make it easy for compiler writers to implement new using malloc, and this is the defined behavior for malloc.

The GCC c compiler docs give this reason: "Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object: "

struct line {
  int length;
  char contents[0];
};

struct line *thisline = (struct line *)
  malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

[without it], you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.

Gonen I
  • 5,576
  • 1
  • 29
  • 60
0

My professor told me that because c++ and c can access and write outside of array bounds,it is one of the main reasons they are used to create operating systems. For example you can even do something like

arr[-1]=5;

I believe it is worth mentioning.However this can lead to undefined behavior.

John M.
  • 245
  • 1
  • 3
  • 13