char* pointers between C and D

pascal111 judas.the.messiah.111 at gmail.com
Mon Jul 25 11:14:56 UTC 2022


On Monday, 25 July 2022 at 09:36:05 UTC, ryuukk_ wrote:
> Here is the way to do it with `writefln` (i think)
>
>
> ```D
> import std;
> import core.stdc.string;
>
> void main()
> {
>     const(char)[] ch = "Hello World!";
>     const(char)[] ch2 = "abc";
>     const(char)* p;
>
>     p = &ch[0];
>     p++;
> 	
>     auto str = p[0 .. strlen(p)];
>     writefln("%s", str);
> }
> ```
>
> Note that i removed your `.dup` it is unecessary, string 
> literals needs `const(char)`
>
> After looking at the doc, `writefln` needs a slice, so we just 
> do that and pass it

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


More information about the Digitalmars-d-learn mailing list