Array-initialization

torhu no at spam.invalid
Thu Oct 9 16:50:31 PDT 2008


Hendrik Renken wrote:
> Hi,
> 
> i have a question regarding array-initialization.
> 
> 
> consider:
> 
> struct STRUCT
> {
>      byte[] data;
> }
> 
> 
> STRUCT foo(byte[] myData)
> {
>      STRUCT* s = new STRUCT(myData);
> }
> 
> 
> do i now create a struct with an array on the heap and then drop the 
> array and assign to the array-pointer the array "myData"? If yes, how 
> can i avoid the creation and deletion of the array "data" in the first 
> place? Am i right, that the variable "data" only holds a pointer to the 
> real array?

"data" is a dynamic array reference, so STRUCT is really just this:

struct STRUCT
{
   size_t length;
   byte* ptr;
}


So "data" is just a number of elements and a pointer to the first one. 
When you do "new STRUCT(myData)", you're only allocating room for that. 
  There's no room for array contents  allocated, just the reference.

If you do writeln(STRUCT.sizeof); it will always say 8 on a 32-bit 
system, same goes for data.sizeof.


Your example should probably look like this, as there's no point in heap 
allocating small structs:


STRUCT foo(byte[] myData)
{
      STRUCT s = STRUCT(myData);
}


More information about the Digitalmars-d-learn mailing list