View RSS Feed

Development Team Blog

Converting a String to Char[]

Rate this Entry
In the last article I mentioned that the Address type can be used to efficiently copy a Char[] containing a null terminated C string to a VDF String, and I also mentioned that it works the other way around. A follow-up question I received (and should have predicted) was about exactly how you can do that.

Basically, the task is to quickly and efficiently copy a VDF String to a Char[]. The first solution one might come up with is to loop through the characters in the string and assign the array element by element. This works perfectly fine, but if it's a performance critical piece of code, and you're repeating this process over and over, you might want to find a faster solution.

I mentioned that you have to be careful, and you have to make sure the Char[] is large enough to hold the string (including the null terminator), there's no automagic resize when going this way around.

So without further ado, here's the code for the reverse logic of last time:

Procedure TestIt
    Char[] myCharArray
    Address pStr
    String sStr
    Move "Hello" to sStr

    //Allocate a buffer large enough to hold the string, plus a null terminating character
    Move (ResizeArray(myCharArray,Length(sStr)+1)) to myCharArray
    //Treat the Char[] as a null terminated C string and quickly copy the String variable to it
    Move (AddressOf(myCharArray)) to pStr
    Move sStr to pStr

    //Display the null terminated string to prove it worked
    Showln pStr
Another follow-up question I received was whether you really have to use ResizeArray(), or if you could use a static array instead. The answer is that you don't necessarily have to use ResizeArray(), and you can use a static array (such as Char[255]), but what you have to do is "make sure the Char[] is large enough to hold the string (including the null terminator)". Exactly how you accomplish that task is up to you, but it's your responsibility to make sure the buffer really is large enough, one way or another.
Tags: sonny falk