On Monday, 25 July 2022 at 13:51:35 UTC, ryuukk_ wrote:
On Monday, 25 July 2022 at 11:14:56 UTC, pascal111 wrote:
On Monday, 25 July 2022 at 09:36:05 UTC, ryuukk_ wrote:
[...]

I tried your advice with two ways; once with a constant and other with an array, but the result isn't the same. The array case has more letters in the output.


module main;

import std.stdio;
import core.stdc.stdio;
import core.stdc.string;

int main(string[] args)
{


        const(char)[] ch1 = "Hello World!";
        char[] ch2="Hello World!".dup;

        const(char) *p1;
        char *p2;

        p1=ch1.ptr;
        p2=ch2.ptr;

        writeln(p1[0..strlen(p1)]);
        writeln(p2[0..strlen(p2)]);

        return 0;
    }


Runtime output:

https://i.postimg.cc/sfnkJ4GM/Screenshot-from-2022-07-25-13-12-03.png

`ch1`is a string literal, just like in C, it is null terminated

`ch2` is a GC allocated char array, it is NOT null terminated

`strlen` is the lib C function, it counts strings up to `\O`

for `p1` it'll print correctly, it is a pointer from the null terminated string

for `p2` strlen doesn't make sense, since it is a pointer from a string that is NOT null terminated

Yes, I have to add "\0":

module main;

import std.stdio;
import core.stdc.stdio;
import core.stdc.string;

int main(string[] args)
{


        const(char)[] ch1 = "Hello World!";
        char[] ch2="Hello World!".dup;

        const(char) *p1;
        char *p2;

        ch2~="\0";

        p1=ch1.ptr;
        p2=ch2.ptr;

        writeln(p1[0..strlen(p1)]);
        writeln(p2[0..strlen(p2)]);

        return 0;
    }

Reply via email to