Pointers- Confused and hating them

Dan murpsoft at hotmail.com
Wed Jan 2 20:14:08 PST 2008


Alan Smith Wrote:

> Hello everyone!

Hello Alan, welcome to programming.

> 
> I am trying to create a cleaner version of dstring. My version, like the original, uses an union to store the string.

You're creating your own to learn, or to accomplish something?  Either way, the best reference is the original if you get stuck.  Starting off, you're not about to face licensing issues, so DMD front-end is GPL.

> 
> union
> {
>  char* _cptr;
>  wchar* _wptr;
>  dchar* _dptr;
> }

That thing will produce one pointer, which can point to any of a char, wchar or dchar.

> I tried to transition from Objective-C to C++ so I could write cross-platform code. 

If you're having issues with unions and pointers, don't worry about cross platform just yet unless you have to for work or something.

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? 

There's only one pointer there.  All the items in a union get put in the same spot, and the size of the union is the same as the size of it's biggest item.

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)

That says "if the first charcode in the string isn't 0".  You'll find if the first two characters are 0, you can use wchar, and if the first 4 are 0, you can use dchar.

> // _cptr is the one I want
> 
> I consider that ugly and would like to know if there is a better way to do it.
> 
> #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. 

If you want to differentiate between types in a union while your program is running, you may need to enumerate the possible types and store an int with the pointer to say which one it is.  (if it's 0, it's a char[], if it's 1, it's a wchar[], etc.

>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?
> 
> 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!

Good effort, m8.

> Peace, Alan

Good luck.



More information about the Digitalmars-d mailing list