Using array slices with C-style fread() from file

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 21 12:01:19 PDT 2017


- Fixed-length arrays are value types. You may not want to return them 
if n is very large.

- Every array has the .ptr property that gives the pointer to the first 
element.

- What can be helpful to you here is the fact that you can treat any 
memory as a slice:

import core.stdc.stdlib;

struct S {
     double d;
}

void main() {
     ubyte * p = cast(ubyte*)malloc(10);
     ubyte[] slice = p[0..10];    // 10 is number of elements

     // Another example with a struct object:
     auto objectCount = 7;
     S * objects = cast(S*)malloc(objectCount * S.sizeof);
     auto S_slice = objects[0..objectCount];
}

Of course, you must be careful with slice lifetimes in this case; you 
shouldn't use the slices after freeing the memory.

Ali



More information about the Digitalmars-d-learn mailing list