C tips (again)

bearophile bearophileHUGS at lycos.com
Sun May 3 03:19:08 PDT 2009


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



More information about the Digitalmars-d mailing list