Is there an easy way to convert a pointer to malloc'd memory to an array?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 24 16:11:11 PDT 2016


On Tuesday, May 24, 2016 19:52:17 Era Scarecrow via Digitalmars-d-learn wrote:
> On Tuesday, 24 May 2016 at 18:43:22 UTC, Adam D. Ruppe wrote:
> > On Tuesday, 24 May 2016 at 18:42:41 UTC, Gary Willoughby wrote:
> >> I have a T* pointer to the start of a malloc'd chunk of
> >> memory, the type T and the number of T's stored in the chunk.
> >>
> >> Is there an efficient way of converting this information to a
> >> D array of type T[] or even T[n]?
> >
> > Slice it:
> >
> > T[] = t[0 .. n];
>
>   You can do that??? I thought slices weren't allowed on raw
> pointers. You just blew my mind away!

A dynamic array is basically just

struct Array(T)
{
    size_t length;
    T* ptr;
}

It can point to any memory. Much as its the default, a dynamic array does
not need to be backed by GC-allocated memory. It's just that unlike when
it's backed by GC-allocated memory, you have to worry about keeping track of
whether that memory is currently being used and when it needs to be freed,
and the dynamic array is guranteed to not have enough capacity to grow in
place, so any kind of array operation that would require growing the array
(e.g. calling reserve or appending) would be guaranteed to reallocate,
whereas when the dynamic array is backed by GC-allocated memory, it may or
may not have to reallocate when you do something like append to it or call
reserve. But aside from worrying about keeping track of its original memory,
having a dynamic array backed by malloc-ed memory is basically semantically
identical to having it backed by the GC. T[] really doesn't care what memory
it refers to. It works either way as long as the memory it refers to
continues to be valid.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list