7/29 I want to zero-initialize an array of somewhat large structs.
What's the best, most portable way to do so? C++, embedded
systems, stack-based array. TIA.
\_ memset()?
\_ the best way is probably to have a brace initializer
that initializes the first struct explicitly (to all 0's).
the rest of them will then be default initialized (to all 0's).
this is also most portable because it will take into account
weird systems, where e.g., the null pointer is not
internally represented by all-bits-zero. -jl
\_ do you mean MyStruct array[100] = { }; or
MyStruct array[100]; array[0] = { }; ?
\_ the former, though I meant you should have something
in between the braces to initialize the first element.
actually, gcc seems to accept just the braces, but
looking at the grammar, this appears not to be legal.
someone feel free to clarify this point. also note that
your latter option is assignment, not initialization. -jl
\_ It's legal as written -- an empty initializer list is
explicitly allowed. --mconst
\_ reference? section 6.5.7 of the c standard doesn't
appear to mention any such thing, nor does the
grammar.
\_ The original poster asked about C++; the C++
standard allows it (8.5, paragraph 1). It's
not allowed in C. --mconst
\_ C++
\_ not portable
\_ Yes, portable.
\_ do you mean all-bits-zero or each field in each struct assigned
to zero? If the former, why not use memset?
\_ Sorry, I'm not that great at this-- is there a difference
b/w all bits zero and all fields zero? I really just want
to initialize it to something "non-garbage" to distinguish
between a struct that's been written to and one that has not
been. Thanks
\_ Yes. null pointers are not necessarily all-bits-zero.
floating point numbers have two representations for the
value 0 (although one of them is all-bits-zero).
\_ they are the same in c++. 0 is guaranteed to convert to
the null pointer [conv.ptr].
\_ To be pedantic, any constant integer expression which
evaluates to 0 is guaranteed to convert to the null pointer
(say, (1-1) for example). |