Is there an equivalent to toStringz for wide strings?
Jonathan M Davis
jmdavisProg at gmx.com
Mon Apr 4 16:53:07 PDT 2011
On 2011-04-04 16:44, Andrej Mitrovic wrote:
> On 4/5/11, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > Not to mention, in the case above, a null
> > character should automatically be appended onto the end of the string,
> > since it's as string literal.
>
> I've always found this confusing. So If I have this char array:
> char[] foostring = "foo".dup;
>
> null is appended to it? So what happens to the null terminator if I
> append another string to foostring? And if I do a copy, e.g.
> foostring[0..$], does this still copy a null terminator?
The null terminator is not actually part of the string. It's one beyond the
end. In effect, it's "foo"[$] (though that would probably throw as long as
array bounds checking is turned on). So, any array operations that you do on
the string will lose the null terminator. It's just that if you pass it to a C
function or some other function that's going completely off of the pointer
(rather than the D array) and which hasn't been told the length of the string,
it's going to see the null terminator at one past the end of the actual array.
So, you can do something like
printf("hello world\n");
or
auto s = "hello world";
printf(s.ptr);
But as soon as you do anything which would cause the array to reallocate or be
copied, you lose the null terminator. It's not really part of the string. It's
one past the end of the string and is there purely for convenience when
dealing with C functions. So, it's lost as soon as you start treating the
string a as D string and do any array or string operations on it which would
copy or change it.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list