Casting pointers

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 27 04:39:00 PDT 2015


On Wednesday, 26 August 2015 at 12:14:54 UTC, John Burton wrote:
> This would be undefined behavior in c++ due to aliasing rules 
> on pointers. It appears to "work" reliably in D when I try it, 
> but that's obviously no guarantee that it's correct or will 
> continue to do so.
>
> Is this correct code in D? And if not, what should I do instead 
> to cleanly and efficiently extract structured data from a 
> sequence of bytes?
>
> import std.stdio;
>
> struct data
> {
>     int a;
>     int b;
> }
>
> void main()
> {
>     byte[] x = [1, 2, 3, 4, 5, 6, 7, 8];
>
>     data* ptr = cast(data*)(x);
>     printf("%x %x\n", ptr.a, ptr.b);
>
> }

This would perhaps be safer:

import std.stdio;

struct Data
{
     int a;
     int b;
}

void main()
{
     byte[] x = [1, 2, 3, 4, 5, 6, 7, 8];

     Data* data = cast(Data*)(x[0..Data.sizeof].ptr);
     printf("%x %x\n", data.a, data.b);
}


More information about the Digitalmars-d-learn mailing list