digitalmars.D.learn - .sizeof dynamically allocated array
- Adel Mamin (9/9) Jun 11 2015 import std.stdio;
- Meta (14/23) Jun 11 2015 ubyte[] is a slice, which is actually a struct. It's more or less
- Adam D. Ruppe (10/11) Jun 11 2015 sizeof is tied to *type*, not a variable. (I kinda wish a1.sizeof
import std.stdio;
void main()
{
ubyte[] a1 = new ubyte[65];
ubyte[65] a2;
writeln("a1.sizeof = ", a1.sizeof); // prints 16
writeln("a2.sizeof = ", a2.sizeof); // prints 65
}
Why a1.sizeof is 16?
Jun 11 2015
On Thursday, 11 June 2015 at 20:09:38 UTC, Adel Mamin wrote:
import std.stdio;
void main()
{
ubyte[] a1 = new ubyte[65];
ubyte[65] a2;
writeln("a1.sizeof = ", a1.sizeof); // prints 16
writeln("a2.sizeof = ", a2.sizeof); // prints 65
}
Why a1.sizeof is 16?
ubyte[] is a slice, which is actually a struct. It's more or less
the same as:
struct Slice(T)
{
T* ptr;
size_t length;
}
So sizeof returns the size of the struct, not the size of the
data that its ptr member points to.
ubyte[65] is a static array, which is just a big block of data on
the stack. That's why it returns the expected value for sizeof.
To create a slice of a static array, use the slice operator:
writeln(sizeof(a2[])); //Prints 16
Jun 11 2015
On Thursday, 11 June 2015 at 20:09:38 UTC, Adel Mamin wrote:Why a1.sizeof is 16?sizeof is tied to *type*, not a variable. (I kinda wish a1.sizeof was prohibited, forcing you to say typeof(a1).sizeof so it is clear but whatever). A dynamic array's size is the length variable plus the pointer variable. A static array's size is the content itself. If you want the size of the content in bytes, best way is to do (cast(ubyte[]) a1[]).length or somethign like that - use the length property instead of sizeof.
Jun 11 2015









"Meta" <jared771 gmail.com> 