Pointers- Confused and hating them

0ffh frank at youknow.what.todo.interNETz
Wed Jan 2 19:09:21 PST 2008


Alan Smith wrote:
> Hello everyone!
> 
> I am trying to create a cleaner version of dstring. My version, like
> the original, uses an union to store the string.
> 
> union { char* _cptr; wchar* _wptr; dchar* _dptr; }
> 
> I tried to transition from Objective-C to C++ so I could write
> cross-platform code. Objective-C can use pointers but I didn't ever
> need to. Now that I am trying to duplicate the small size of dstring
> with pointers, the way dstring does it, I'm getting lost. There are a
> couple things I need to know about using unions and pointers.
> 
> #1 How do I figure out which of the three members in the union are
> used? I tried comparing each to null (if (_cptr !is null) return
> _cptr;...) but that didn't work, they weren't null, the wrong one had
> a small piece of the string in it. My test got worse and worse but
> now finally works. Here is one of the ifs:
> 
> 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.

It nearly 4 am and I have found I have a tendency to write before read,
but let's see: First of all, the union won't tell you which member is
used. What you're doing right now is you are going by the thing the
pointer points to. It's the same as ((*_cptr)!=0). That might actually
work on utf-8 encoded text, if you test in order from the smallest
(char) to the biggest (dchar) member.

> #2 How do I change the pointer I'm using from the union? I want to
> change from one union member to another. For example, the current
> string has a char[] type. I then alter one of the characters (e.g.
> str[0] = 'ൠ') and so the type needs to be changed to wchar[].
> How should I do this? How should I change the union member I am
> using?

All three union members are "alive" all the time, in the sense that
you can assign to them and use them in any legal way. Just remember
that if you assign to _one_ member in the union, you will change
_all_ of them. If you want to keep track of which union member is
the one you want to use you either 1) wrap the union in a struct
with an enum or something telling you which member is currently
"in use" or 2) judge by the data, as it seems you're doing.

> Many thanks, I have been working on this all day and have done lots
> of archive searching to no avail. You're help will be *greatly*
> appreciated!

I sure hope I could cast some light... =)

> Peace, Alan

regards, frank




More information about the Digitalmars-d mailing list