March 19, 2003 Re: Question about casts | ||||
---|---|---|---|---|
| ||||
Posted in reply to Patrick Down | > This is a very common mistake. D strings are
> not null terminated, except for the constant
> ones defined inline. Try this instead.
>
> printf("%.*s\n",two);
>
>
Is that a period and an asterisk following the percent sign? Or is it just an asterisk?
|
March 19, 2003 Re: Question about casts | ||||
---|---|---|---|---|
| ||||
Posted in reply to John Reimer | A period and an asterisk. "John Reimer" <jjreimer@telus.net> wrote in message news:b58hah$1mjl$1@digitaldaemon.com... > > This is a very common mistake. D strings are > > not null terminated, except for the constant > > ones defined inline. Try this instead. > > > > printf("%.*s\n",two); > > > > > > Is that a period and an asterisk following the percent sign? Or is it just an asterisk? > > > |
March 19, 2003 Re: Question about casts | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steve Adams | You need to use the "%.*s" syntax to use only the contents of the slice. "%s" uses a char * - which you've cast it to - and since the slice is a copy-on-write view into the original array, you get the rest of the original because a null-terminator is not contained in the slice. If you want a slice that you can treat as a ZTS, you need to append the null terminator with two ~= (char)0; (although I may be wrong - it's been a while) "Steve Adams" <adamss@ascinet.com> wrote in message news:b58ekm$1kqe$1@digitaldaemon.com... > Can someone clear this up for me? The following code doesn't work the way that I would expect from the description of slices. > > > int main() > { > char[] one = "abc\ndef\n"; > char[] two = one[0..3]; > printf( "%s\n", cast(char *) one ); > return( 0 ); > } > > generates as output > > abc > def > > instead of just > abc > > > |
March 19, 2003 Re: Question about casts | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steve Adams | Steve Adams wrote: > Seems like it's a pointer and a count (since strings are counted). Not a > bad model, until > you want to print it out. I'm working around it with > > printf( "%.*s\n", two.length, (char *)two ); > but that seems rather wasteful. Either the cast should really do a case, or > there should be > a format specifier for the counted strings. > > Might be a way to do this with an array copy too I suppose. This works, but not on Linux. The solution I use (which has a performance hit, unfortunately) is: printf("%s\n", (char*)(two~\0)); Appending to the array causes a copy to be made, so this doesn't overwrite 'one'. -- The Villagers are Online! villagersonline.com .[ (the fox.(quick,brown)) jumped.over(the dog.lazy) ] .[ (a version.of(English).(precise.more)) is(possible) ] ?[ you want.to(help(develop(it))) ] |
Copyright © 1999-2021 by the D Language Foundation