Pointers- Confused and hating them

Derek Parnell derek at nomail.afraid.org
Wed Jan 2 21:20:21 PST 2008


On Wed, 02 Jan 2008 21:08:36 -0500, Alan Smith wrote:

> Hello everyone!
> 
> I am trying to create a cleaner version of dstring ...
> 
> union
> {
>  char* _cptr;
>  wchar* _wptr;
>  dchar* _dptr;
> }

> #1 How do I figure out which of the three members in the union are used?

A union is a list of things that all share the same RAM location. In this
case here, the address of _cptr, _wptr, _dptr is identical, because they
are in the union. And because there are all pointers, the are all the same
length. This means that you cannot use these fields to know if which one is
the 'current' string type. 

The commonly used way of doing this is to use a struct as well as the union
...

struct MyString
{
 union
 {
  char* _cptr;
  wchar* _wptr;
  dchar* _dptr;
 }

 enum StrType {utf8, utf16, utf32};
 StrType _using;
}

Then when you set one of the union fields, you also set '_using' to the
appropriate value. 

eg.
   MyString s;
   char[] c;

   
   s._cptr = c.ptr;
   s._using = MyString.StrType.utf8;


   if (s._using == MyString.StrType.utf8)
        SomeFunc(_cptr);
   else if (s._using == MyString.StrType.utf16)
        SomeFunc(_wptr);
   else if (s._using == MyString.StrType.utf32)
        SomeFunc(_dptr);

 
> I tried comparing each to null ...

Because they share the same RAM location, testing one tests them all. This
method will not work.

> 
> if (*_cptr !is 0)
> // _cptr is the one I want
> 
> I consider that ugly and would like to know if there is a better way to do it.

And dangerous. Not to be used.


-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
3/01/2008 4:09:45 PM



More information about the Digitalmars-d mailing list