Void pointers

Alex via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 16 14:33:03 PDT 2016


On Monday, 16 May 2016 at 21:04:32 UTC, ag0aep6g wrote:
>
> Typo here. Should be `ptr[a .. b]`.
Thanks

>>
>> void main()
>> {
>>      void* ptr; // this will stay uninitialized during the 
>> whole program
>> run
>
> The pointer is being initialized, though. To null, which is why 
> your shenanigans below work reliably.

Ok, this is a cool hint, especially about the reliability. Thanks!

>
>>      // something that works as desired:
>>      writeln(&ptr[4]); // prints '4'
>>      auto b = getSlice(ptr, 5, 10);
>>      writeln("b first: ", &b[0]); // prints '5'. This is the 
>> most useful
>> feature.
>>      assert(b.capacity == 0); // holds always. So, getSlice 
>> returns
>> always a slice, not an array.
>>      // arr[3] = ... // fails. It is intended to do so.
>>
>>      // something that does not worked as expected:
>>      // how to rewrite a for loop
>>      for(auto i = 0; i < b.length; i++) writeln(&b[i]);
>>      // into a foreach loop?
>
> Not, I guess, since you can't have a void variable, not even if 
> it's marked `ref`.

Yes, this is something what I was surprised about, but, seems 
logical on the other hand... So, I get a slice, which is not 
foreachable, but still able to be iterated over...

> I have to say that I don't see the point in all this. You can't 
> access the elements of b in any way, since they're in memory 
> that you don't own. So all you got here is a fancy way of 
> counting, no?

Yes! This is important and this is the place, where I have to 
provide background. (Following post)

>
> Not sure what you mean here. What's the described manner? Not 
> being able to have a variable of the type?

Well... not wanting to have a variable, which stores numbers, 
which are natural numbers, beginning with zero, used for counting 
only.

>
> I think void is the only type with that property. So maybe 
> checking if the type is exactly void is enough: `is(T == void)`.

OK...

> Or you can check if some operation works on the type or a value 
> of it: `__traits(compiles, writeln(T.init))`
>




More information about the Digitalmars-d-learn mailing list