"Is it OK to make a global stack allocated array point to NULL
?"
"Is the init(ialization) of the struct at foo_arr[2]
valid?"
No, it is not OK and not valid. At least not in the way you did (C syntax violation with {NULL}
- it needs to be {{NULL}}
to get compiled).
typedef struct foo
{
bool bar[4];
} foo;
foo foo_arr[] = {
{{true, true, false, true}},
{{false, true, false, true}},
{{NULL}}
};
Indeed, under some requirements this would initialize all elements of bar
to 0
, but lets start at the beginning.
Why would you want to use NULL
? NULL
is used to compare and set pointers, not data objects. bar
is not an array of pointers.
I indeed had a similar question myself, a few months ago:
It is implementation-defined whether it is valid to use NULL
to initialize data objects to 0
, since the NULL
macro either expands to 0
or (void*) 0
. If it is the latter, the implementation needs to specify what happens if you assign a pointer to void
to an integer type.
"Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type."
Source: C18, 6.3.2.3/6
So if either,
NULL
expands to 0
on your specific implementation, or
- The implementation specifies conversions from pointers to integers (the conversion from
(void*) 0
to an data object),
this would indeed initialize all elements of bar
in the third structure to 0
, because of following:
In the first place, {{NULL}}
set the first bool
object in the array bar
in the third structure of the array foo_arr
to 0
.
Implicitly it will also initialize all following three bool
object to 0
, because:
"If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than thereare elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration."
Source: C18, 6.7.9/20
This means if you intialize the first bool
object it will automatically initialize all others.
"If not, what is the correct way to point such array to NULL
?"
As said above, not to NULL
, to 0
or false
. The array (elements) do not point to anywhere. They are not pointers! As indicated above you can just use {{0}}
or {{false}}
:
typedef struct foo
{
bool bar[4];
} foo;
foo foo_arr[] = {
{{true, true, false, true}},
{{false, true, false, true}},
{{0}};
};