On Tue, 22 Sep 2009 09:53:52 -0400, Justin Johansson
<[email protected]> wrote:
Daniel Keep Wrote:
> Big difference if you pass char[] variable .ptr to a C function.
In general, if you pass a string to a C function you should send it
through toStringz first. If you don't, you're just begging for
segfaults.
Agreed .. fair enough.
Actually I'm more interested in the semantics for default initialized
char[].
Does it have exactly the same semantics as an empty string (in general D
or runtime library, Phobos et. al. context)?
A null string *is* an empty string, but an empty string may not be a null
string.
The subtle difference is that the pointer points to null versus some data.
A non-null empty string:
- May be pointing to heap data, therefore keeping the data from being
collected.
- May reallocate in place on appending (a null string always must
allocate new data on append).
It's a difficult concept to get, but an array is really a hybrid type
between a reference and a value type. The array is actually a value type
struct with a pointer reference and a length value. If the length is
zero, then the pointer value technically isn't needed, but in subtle
cases, it makes a difference. When you copy the array, the length behaves
like a value type (changing the length of one array doesn't affect the
other), but the array data is referenced (changing an element of the array
*does* affect the other).
I think plans are to make the array a full reference type, and leave
slices as these structs (in D2). This probably will clear up a lot of
confusion people have.
I hope this helps...
Oh, and BTW, you can pass string literals to C functions, but *not* char[]
variables. Always pass them through toStringz. It generally does not
take much time/resources to add the zero.
-Steve