std.file.read returns void[] why?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 18 06:08:04 PDT 2014


On Fri, 18 Apr 2014 02:04:16 -0400, monarch_dodra <monarchdodra at gmail.com>  
wrote:

> On Thursday, 17 April 2014 at 21:27:44 UTC, Steven Schveighoffer wrote:
>> On Thu, 17 Apr 2014 17:04:25 -0400, monarch_dodra  
>> <monarchdodra at gmail.com> wrote:
>>> void[] will only make sense once you've accepted that "void.sizeof ==  
>>> 1".
>>
>> It is already accepted that when we talk about length in a void[], it's  
>> the number of bytes. But the data has no formal type.
>
> Well, I always thought that "void[] slice" meant "there are slice.length  
> items, starting at slice.ptr. I don't know the size of the individual  
> items".
>
> For example, in C, a lot of functions take "void* first, size_t num,  
> size_t width".
>
> In fact, most of druntime functions take "void[]" buffers that work that  
> way. There's an associated typeid, so that you can now how large each  
> individual items are.

import std.stdio;

void main()
{
    int[] x = new int[5];
    void[] y = x;
    writeln(y.length); // 20
}

When a function takes a typeid, that usually is because the translation is  
not made. In druntine cases, the compiler is removing the type, and  
sticking it into the typeid instead. But the length has not been  
translated to bytes! It's still in terms of the original type.

In those cases, it's equivalent to:

void[] y = *cast(void[]*)&x;

which would make y.length == 5.

>> But any array implicitly casts to void[]. This is why it makes a good  
>> parameter for read or write (when reading or writing the binary data).
>
> I guess. I just find it kind of strange that a type "that has no type"  
> would have an actual sizeof. Then again, I thought void had no sizeof in  
> C, but I just checked, and I was wrong.

It's a little strange, but while void has no size, void[] *does* have a  
size. The size is in bytes. You can think of an array as "starts at this  
address, and ends at that address". Because addresses are in terms of  
bytes, so is the length of that array.

I admit, I didn't think C's void had a size ;) I'm pretty sure it doesn't  
in D, but then again...

-Steve


More information about the Digitalmars-d-learn mailing list