-4

The following code compiles and outputs 6:

#include <stdio.h>

int main(){
 int a[]={};
 a[0] = 5;
 a[1] = 6;
 printf("%d\n", a[1]);
 return 0;
}

Is this correct or am I getting into undefined behaviour and this code woks by luck? Can I add to an array with no size?

Josh
  • 43
  • 1
  • 4
  • 3
    This should not compile as C++ code, as C++ does not support zero-length arrays. And there is no such language as "C/C++" - pick one. –  Jul 13 '19 at 22:28
  • 2
    *"C++ does not support zero-length arrays"* Neither does C. If we ignore that, then yes, you get UB because you access the array out of bounds. Size of an array can't be changed (and in C++ it has to be a compile-time constant). – HolyBlackCat Jul 13 '19 at 22:30
  • @Holy How can you get UB from code that won't compile? –  Jul 13 '19 at 22:32
  • It does compile and run in C++. – Josh Jul 13 '19 at 22:32
  • 1
    Then there is something wrong with your compiler. –  Jul 13 '19 at 22:32
  • @Neil [In Clang it compiles, but produces a warning](http://coliru.stacked-crooked.com/a/a75b86ba6b8b9581). – zett42 Jul 13 '19 at 22:33
  • @NeilButterworth By *"If we ignore that"* I meant 'If we ignore the zero-length array making the program ill-formed'. :) – HolyBlackCat Jul 13 '19 at 22:33
  • @Josh Most compilers are lenient by default (they sometimes accept programs that the C/C++ standards consider ill-formed). You can change your compiler settings to make it be more strict about the C/C++ standard conformance. – HolyBlackCat Jul 13 '19 at 22:35
  • The canonical SO answer on this sort of problem in C is [here](https://stackoverflow.com/questions/15646973/). – Steve Summit Jul 13 '19 at 23:16

2 Answers2

4
int a[]={};

The program is ill-formed. There may not be arrays of size zero with local (or static) storage. (Dynamic arrays of zero size are allowed, though I haven't found use for them).

am I getting into undefined behaviour

a[0] = 5;
a[1] = 6;

You access elements outside the bounds of the array. The behaviour of the program is undefined.

Adding to an Array

Can I add to an array...?

It is not possible to add elements to an array. The size of an array remains constant throughout its entire lifetime.

What you can do is dynamically create a new array that is larger, and copy the elements from the old array to the new one. There is a standard container that implements this: std::vector.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
0

This is a UB.

Array in stack is not a good idea too, use vector instead.

std::vector<int> vec = {};
vec.push_back(5);
Oblivion
  • 7,176
  • 2
  • 14
  • 33