.ptr and .value

Robert Clipsham robert at octarineparrot.com
Wed May 5 15:42:21 PDT 2010


On 05/05/10 23:20, strtr wrote:
> I keep on expecting .ptr to work on all types. What keeps this from being the case?
> And how about having a .value(.deref) property for known pointers?
>
> I feel a lot less comfortable with using stars and ampersands, because I keep on forgetting which one does what.

.ptr is only available for arrays. Internally, (dynamic) arrays in D 
look like this:
----
struct {
   size_t length;
   T* ptr;
}
----
Where T is the type of the array. This is why you can use .ptr on it. 
For other types they are types on their own, so don't have such 
properties. As for .value and .deref, these won't be implemented, you'll 
have to live with & and * if you want to use pointers. Note that if 
you're using pointers you should be comfortable with them, if you're not 
it's probably best to avoid them. In fact, D makes it easy to do so!

As for referencing/dereferencing:
----
int myInt = 6;
int* ptrToMyInt = &myInt; // & takes a reference to myInt, making
                           // this a pointer
int myInt2 = *myInt; // myInt2 == 6, * dereferences.
----

Again, let me reinforce that you don't need to use pointers in D, 
they're easy to avoid in most cases... Feel free to play with them, and 
as you gain confidence you may find uses for them :) When I first 
learned how to use pointers I found this little video/tutorial a fun 
intro to them, you might like to take a look: 
http://cslibrary.stanford.edu/104/ :)


More information about the Digitalmars-d-learn mailing list