0

I've a question about array definition. I've tryed two types of definition:

First definition

uint8_t data_i2c[1] = { 1 };

Second definition

uint8_t data[1];
data[0] = 1;
data[1] = 2;

In the first case I've an array of 1 value, if I add another value(ex. { 1, 2 }; ) I've a compiling error. In the second case I've defined array in the same way, but I've added values in a second time, If I add another value(ex. data[2] = 3; ), I've not a compiling error.

Why this difference?

I've also checked in debug and even if I define:

data[1] = 2;
data[2] = 3;

I can see only data[0] = 1;

I remember that if I define any array I always have and can use value in index 0.

I'm using Atmel Studio as compiler and C language.

Singe
  • 153
  • 1
  • 5
  • Because [*undefined behaviour*](https://en.wikipedia.org/wiki/Undefined_behavior) doesn't necessarily produce a compiler time error/warning. – P.P Nov 25 '15 at 11:35

2 Answers2

0

In your code

uint8_t data_i2c[1] = { 1, 2};

will give you a warning (may give you an error, too, based on your compilation options), because, you're using excess initializer element than that of the size of the array.

OTOH, in case of

uint8_t data[1];

and

data[1] = 2;

because, you're trying to access out of bound memory, which is not prohibited by the C standard (C arrays does not have any boundary overrun checking by default, remember?) but defined to produce undefined behavior.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

In first case initializer is used. At compile time compiler calculates that elements in the initializer list is more than that of the array size and hence produce error.

In second snippet, assignment is performed at run time and out of bound of array writing is performed. Compiler has know way to know that you are accessing array out of bound.

haccks
  • 104,019
  • 25
  • 176
  • 264