0

I have the following code and I am unsure on whether this is safe or not?

uint8_t array1[3];
uint8_t array2[3];
///Array containing the above arrays to simplify selection
uint8_t *array_of_arrays[2]
    = {array1, array2};

void initialize_array(uint8_t array_id)
{
    array_of_arrays[array_id][0] = 0;
    array_of_arrays[array_id][1] = 1;
    array_of_arrays[array_id][2] = 2;
}

Is the address of array1 and array2 defined and valid when they are later initialized in initialize_array()? I had read somewhere that space is only allocated at the time of initialization/definition and not at declaration, which I think I have with uint8_t array2[3];. Is that true for arrays as well? If so, then is A better or B? Is there any difference?

A:

uint8_t array1[3] = {0,1,2};
uint8_t array2[3] = {0,1,2};
///Array containing the above arrays to simplify selection
uint8_t *array_of_arrays[2]
    = {array1, array2};

B:


uint8_t array1[3];
uint8_t array2[3];
///Array containing the above arrays to simplify selection
uint8_t *array_of_arrays[2];
void initialize_array(uint8_t array_id)
{
    if (0 == array_id)
    {
        array1[0] = 0;
        array1[1] = 1;
        array1[2] = 2;
        array_of_arrays[0] = array1;
    }
    else
    {
        array2[0] = 0;
        array2[1] = 1;
        array2[2] = 2;
        array_of_arrays[1] = array2;
    }
}
  • @rici I am adding better dupes. @-OP it is always fine to take a reference or a pointer to an uninitialized variable. [Why it is ok to pass an uninitialized variable address to pointer paramter of a function](https://stackoverflow.com/questions/62649733/why-it-is-ok-to-pass-an-uninitialized-variable-address-to-pointer-paramter-of-a) – Jason Oct 25 '22 at 04:42
  • Also note that in C, the lifetime of an automatic variable starts when you enter the block in which the variable is declared, unless the variable is variably modified (i.e. a VLA). However, since it's not yet in scope before it's declared, you can't textually refer to it. But you can jump over a declaration with a `goto` (except for VLAs), and if you do that, you'll find that the variable hasn't been initialized, but it's address is still fine. – rici Oct 25 '22 at 04:43
  • According to C standard, if you *can* take an address of a variable then **then** that variable *will have an address*, and the address will be constant throughout its lifetime. You must not access the object *after* its lifetime though (none presented in the examples) – Antti Haapala -- Слава Україні Oct 25 '22 at 05:03

0 Answers0