2

I have this struct:

typedef struct {
    GPIO_TypeDef* GPIO_Reg;
    uint16_t GPIO_Pin;
    uint16_t status;
} PinType;

Then if I declare this array:

PinType array[10];

The PinType elements in the array are initialized with some default values?

For example, if I write this:

printf("%d", array[1].status);

Should I see 0 as output? Or the initial value depends on the content of the memory before I declared the array?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
PaulRox
  • 79
  • 1
  • 9

2 Answers2

6

This answer depends on the scope of the variable.

  • if array is global, then it will be auto-initialized.
  • if array is static, all the elements will be auto-initialized to 0.
  • if array is of automatic storage, it won't be initialized automatically.
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Plus one; the first one is often forgotten – Bathsheba Jul 13 '15 at 12:41
  • So if my array is global if i try to do that printf I should always receive a "0"? And if it is true, this is a feature i can rely on? I mean, it is in some way compiler-dependent or it is defined by the C standard? – PaulRox Jul 13 '15 at 13:00
2

The structure members are not initialised, unless the variable is static or global.

In fact, using an uninitialised member is undefined behaviour in C.

memsetting the array with zeros is idiomatic.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483