Skip to main content
Graduate II
November 3, 2024
Question

Array initialization

  • November 3, 2024
  • 2 replies
  • 1457 views

I know that the question will be trivial, however, I do not understand why the instruction uint8_t dataRx[4] = { 1 }; does not initialize all the elements of an array to 0 ... but only the first one:

stm32 array 2.png

I have programmed little in the last while so I will probably misremember myself, however I was almost convinced that such instruction initialized the whole array to zero ... as also written here.

The two arrays in the picture (let's consider only array2) are inside a function of a sensor library that, at this point, I don't know if it is intended to initialize to 1 only the first element or all the elements of array2 ..

In any case I solved it using:

memset 

 

To recap, is the fact that the uint8_t dataRx[4] = { 1 } instruction does NOT initialize all elements to 0 an error on my part or is this likely to happen on other compilers?

    This topic has been closed for replies.

    2 replies

    Super User
    November 3, 2024

    Correct. Only the first element will be initialized (edit: to 1). And yes, its the law: Array initialization - cppreference.com

    hth

    KnarfB

    Graduate
    November 3, 2024

    All the elements are initialized, the first one to 1, others to zeros. That's the standard behavior and every compiler must do that.