0

I'm initializing my array to a size of 3 and then assigning 5 elements in it.

uint8_t test[3] = {};

for (i = 0; i <= 5; i++)
{
    test[i]= i;
}
Moppo
  • 18,797
  • 5
  • 65
  • 64
spizzak
  • 1,087
  • 1
  • 11
  • 17
  • 1
    Related to: [Is accessing a global array outside its bound undefined behavior?](http://stackoverflow.com/q/26426910/1708801) – Shafik Yaghmour Jul 15 '15 at 14:20
  • also related http://stackoverflow.com/questions/382993/why-do-compilers-not-warn-about-out-of-bounds-static-array-indices?rq=1 – Giorgi Moniava Jul 15 '15 at 15:35

1 Answers1

3

Because C doesn't work that way. As the programmer, you are responsible for making sure the array indexes do not go out of bounds.

One way to get around this is, if you know how long your array needs to be, create a variable and use it in your program like so:

const int ARRAY_LENGTH = 3;

uint8_t test[ARRAY_LENGTH];

for (int i = 0; i < ARRAY_LENGTH; i++)
{
    test[i] = i;
}

That way, if the array length needs to change, you only need to remember to change it in one place instead of every where it is used.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
  • 3
    Honestly, if you don't know, maybe you shouldn't post an answer. Throw the code into a compiler and it will let you know. – this Jul 15 '15 at 14:23
  • That's actually a variable-length array. `ARRAY_LENGTH` is `const` but not constant. It's valid in C99 or later, but not in C90. Consider using s macro or `enum` instead. – Keith Thompson Jul 15 '15 at 14:39