| |
| Posted by Daniel Yokomiso in reply to kw | PermalinkReply |
|
Daniel Yokomiso
| "kw" <kw_member@pathlink.com> escreveu na mensagem news:bjgids$1hdv$1@digitaldaemon.com...
> Why is the following not working? (DMD 0.71)
>
> int main (char[][] args)
> {
> char[] s = "12345";
>
> printf("%s --> ", (char *)s);
> s = s[0 .. s.length-1]; // I want to strip the last char
> printf("%s\n", (char *)s);
> return 0;
> }
>
> It prints 12345 --> 12345
In D arrays are more than pointers, because they carry length information too. But String literals have a additional invisible \0 in the end. So when you say:
> printf("%s --> ", (char *)s);
You are treating the address/length pair that represents the array as a
"char*", so the length info is lost, but the invisible \0 at the end of
"12345" is used to terminate the string inside "printf".
When you slice the array, you just create a new address/length pair, so the
sliced variable
> s = s[0 .. s.length-1]; // I want to strip the last char
Points to the original "12345\0" array, when used as an array it'll give a reduced length. But when you cast it to "char*" the printf will find the \0 only after "5". So you either use "%.*s" instead (that handle "char[]" properly) or use the "toStringz" function from Phobos, that'll give a "char*" with the \0 at the end, so "toStringz(s[0 .. s.length-1])" will return a "char*" pointing a memory location containing "1234\0".
Best regards,
Daniel Yokomiso.
"Lord save me from your followers."
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.514 / Virus Database: 312 - Release Date: 30/8/2003
|