C tips (again)
Denis Koroskin
2korden at gmail.com
Sun May 3 04:22:11 PDT 2009
On Sun, 03 May 2009 14:19:08 +0400, bearophile <bearophileHUGS at lycos.com> wrote:
> Denis Koroskin:
>> Mystring s = ...;
>> char c = s.data.ptr[42];
>
> Thank you for your nice suggestion.
> In Python newsgroups people usually before suggesting any solution try
> to run it to see if it works correctly (this isn't always possible).
>
> The following program doesn't work to me when WITH_PTR is true (Error:
> Access Violation) (to be compiled with -release when WITH_PTR is false):
>
> import std.c.stdio: printf;
> import std.c.stdlib: malloc, exit;
>
> const bool WITH_PTR = 1;
>
> struct Mystring {
> int size;
> int capacity;
> char data[0];
> }
>
> void main() {
> string s = "hello, how are you?";
>
> int total_len = Mystring.sizeof + s.length + 1;
> auto str = cast(Mystring*)malloc(total_len);
> if (str is null) exit(-1);
>
> static if (WITH_PTR) {
> foreach (i, c; s)
> str.data.ptr[i] = c;
> str.data.ptr[s.length] = '\0';
> printf("%s\n", str.data.ptr);
> } else {
> foreach (i, c; s)
> str.data[i] = c;
> str.data[s.length] = '\0';
> printf("%s\n", &(str.data));
> }
> }
>
> Bye,
> bearophile
I use that trick quite often and it works. The problem here is, DMD initialize 0-length static arrays' ptr with null:
void main() {
auto str = cast(Mystring*)malloc(42);
assert(str.data.ptr !is null); // fails
}
I believe this issue needs to be posted to bugzilla.
More information about the Digitalmars-d
mailing list