how to initialize an array of typedef-ed type?

MLT none at anone.com
Fri May 1 08:34:56 PDT 2009


Thanks! Yes - that works.

I have to be careful, though. Thus:

typedef long location ;
location x[] = (cast(location[])[1,2,3,4]).dup ;

works, but

location x[] = cast(location[])[1,2,3,4].dup ;

does not.

I guess there are really two different types of cast - which also confused me in C++:
one is convert: please try to convert type1 to type2.
The other is cast: I know you think this is type1, but I know better, so from now on, call it type2.

Is there an easy way to convert arrays from one type to another?
int[] a=[1,2,3,4] ;
long[] b ;

What is the easiest way to get a into b? 
b[] = a[] 
doesn't seem to work...



Jarrett Billingsley Wrote:

> On Fri, May 1, 2009 at 10:07 AM, MLT <none at anone.com> wrote:
> 
> > At first I thought that maybe on my machine int and long have the same length, or some such. But it works, for int, long, and short. And they do have different lengths.
> 
> D's integer types are not like C's.  They are fixed size and do not
> vary from platform to platform.  See
> http://www.digitalmars.com/d/1.0/type.html
> 
> > I tried a bit more:
> > ---
> > typedef long tlong ;
> >
> > void main()
> > {
> >        int[] x = [1,2,3,4] ;
> >
> >        tlong[] y = cast(tlong[])[1,2] ; // <- this works
> >
> >        Stdout(y).newline ;
> >
> >        y = cast(tlong[]) x ; // This doesn't
> >
> >        Stdout(y).newline ;
> > }
> > ---
> > prints out:
> > [1, 2]
> > [8589934593, 17179869187]
> >
> > The the initialization works, but casting from int[] to long[] in general doesn't.
> 
> You're actually doing two different things there.
> 
> Initialization is treated as a special case and casting it will cast
> each element.
> 
> But array casts done at runtime will do a bit cast - that is, given
> your int[] [1, 2, 3, 4], when you cast it to a long[] at runtime, it
> takes that chunk of memory, figures out how many longs will fit in it
> (in this case 2), and gives you a new array reference to the same data
> but with a different type.  Those big weird numbers are
> 0x00000002_00000001 and 0x00000004_00000003, respectively.  Woah look
> at that, 1, 2, 3, 4!
> 
> To make it more apparent, try casting an int[] to a byte[] or
> something.  You'll see that it then splits up each original int into
> four bytes.



More information about the Digitalmars-d-learn mailing list