filling arrays, avoid default init
Stewart Gordon
smjg_1998 at yahoo.com
Thu Jan 11 09:21:20 PST 2007
Thomas Kuehne wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Lionello Lunesu schrieb am 2007-01-09:
>> Lionello Lunesu wrote:
>>> Frank Benoit (keinfarbton) wrote:
>>>> TypeA[] ta = .... ; // big array with something
>>>> TypeB[] tb;
>>>> tb.length = ta.length; // (1)
>>>> foreach( uint i, TypeA a; ta ){
>>>> tb[i] = ta[i].getB();
>>>> }
>>>>
>>>> (1) how can I avoid the default initialization?
>>>>
>>>> -- Frank
>>> type[] t = void;
>> Uhm, sorry. That doesn't seem to prevent the initialization at all...
Actually, it's unpredictable, even dangerous.
> Can you provide a code sampel?
----------
import std.stdio;
void main() {
int[] data = void;
writefln("%08x %08x", data.ptr, data.length);
data.length = 16;
writefln("%08x %08x", data.ptr, data.length);
writefln(data);
}
----------
You'll be lucky if the last statement doesn't throw an AV. The danger
arises if you try to write to the memory at the uninitialised pointer.
> Tested on Linux:
> # import std.stdio;
> #
> # typedef int X = 12_34_56_78;
> #
> # void main(){
> # X[4] a;
> # X[4] b = void;
<snip>
Of course that works. That's a static array.
Stewart.
More information about the Digitalmars-d-learn
mailing list