On Monday, 25 July 2022 at 09:04:29 UTC, pascal111 wrote:
I have small C program that uses a pointer to change the start address of a string, and when I tried to do the same code but with D, the D code printed the address of the string after I increased it one step instead of printing the string the pointer pointing to. Is there a difference between "char *" pointers between C and D.

No, no difference. Pointers are the same in both languages. What's different is the behavior of `%s` in `writeln` vs `printf`. See the documentation on format strings at:

https://dlang.org/phobos/std_format.html

Essentially, `%s` tells the formatter to output something appropriate for the given type. For an actual D string, you see the text. For an integral or floating point type, you see the number. For a pointer, you see the the address. And so on.

Do in your case, to get `writefln` to print the text instead of the pointer address, you could import `std.string` and use `fromStringz`:`fromStringz(p)`.

This will give you a D string without allocating any memory. Basically an immutable slice of the memory pointed at by `p`. That's fine for this use case, but if you wanted to hang on to the string beyond the lifetime of the pointer, you'd have to use `std.conv.to` instead (e.g., `to!string(p)`).


Reply via email to