Thread overview | |||||
---|---|---|---|---|---|
|
November 10, 2012 Casting an array form an associative array | ||||
---|---|---|---|---|
| ||||
The following example:
void main()
{
void[][size_t] aa;
aa[1] = [1, 2, 3];
if (auto a = 1 in aa)
{
writeln(*(cast(int[]*) a));
writeln(cast(int[]) *a);
}
}
Will print:
[1, 2, 3, 201359280, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 3]
The first value seems to contain some kind of garbage. Why don't these two cases result in the same value?
--
/Jacob Carlborg
|
November 10, 2012 Re: Casting an array form an associative array | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jacob Carlborg | On 11/10/2012 01:20 PM, Jacob Carlborg wrote:
> The following example:
>
> void main()
> {
> void[][size_t] aa;
> aa[1] = [1, 2, 3];
>
> if (auto a = 1 in aa)
> {
> writeln(*(cast(int[]*) a));
> writeln(cast(int[]) *a);
> }
> }
>
> Will print:
>
> [1, 2, 3, 201359280, 0, 0, 0, 0, 0, 0, 0, 0]
> [1, 2, 3]
>
> The first value seems to contain some kind of garbage. Why don't these
> two cases result in the same value?
>
The length of an array is the number of elements. sizeof(void)==1 and sizeof(int)==4. The first example reinterprets the ptr and length pair of the void[] as a ptr and length pair of an int[]. The second example adjusts the length so that the resulting array corresponds to the same memory region.
|
November 10, 2012 Re: Casting an array form an associative array | ||||
---|---|---|---|---|
| ||||
Posted in reply to Timon Gehr | On 2012-11-10 17:48, Timon Gehr wrote: > The length of an array is the number of elements. sizeof(void)==1 and > sizeof(int)==4. The first example reinterprets the ptr and length pair > of the void[] as a ptr and length pair of an int[]. The second example > adjusts the length so that the resulting array corresponds to the same > memory region. Ok, thanks for the explanation. -- /Jacob Carlborg |
Copyright © 1999-2021 by the D Language Foundation