Disallow arrays as pointers

Salih Dincer salihdb at hotmail.com
Sat May 13 13:01:21 UTC 2023


On Saturday, 13 May 2023 at 12:55:24 UTC, Salih Dincer wrote:
> I saw that it was closed today:
>
> https://issues.dlang.org/show_bug.cgi?id=6869

A new issue has been reported by Steven Schveighoffer:

https://issues.dlang.org/show_bug.cgi?id=23919
> Casting an array to a pointer is allowed:
> 
> ```d
> import core.stdc.stdio;
> auto str = "hello";
> printf(cast(char *)str[0 .. 3]);
> ```
> 
> This prints "hello".
> 
> The user might think they have properly matched the 
> requirements, but in
> actuality, all they have done is accessed the pointer.
> 
> A few reasons why this is bad:
> 
> 1. It's trivial (and more readable) to use `.ptr` instead of 
> the cast
> 2. The cast must match the attributes or risk causing problems 
> when code
> evolves. Casting is a blunt instrument, and should be 
> discouraged when
> better alternatives exist.
> 3. The cast gives a false impression that something is 
> happening underneath
> to ensure the data is correct. Many C functions require 
> pointers instead of
> arrays, and this "seems" like the right answer.
> 
> I think we should deprecate this "feature". I'm not exactly 
> sure why this
> was needed in the first place.
> 
> I know a previous issue #6869 was closed as WONTFIX. I'm 
> opening this to
> hopefully reconsider the decision.
> 
> FWIW, the D discord has had a few people coming to ask why 
> their code
> doesn't work when casting a `string` to a `char *`.
> 
> I would pair such a cast error with a suggestion to use 
> `toStringz` in the
> case of string to char * conversions.

SDB at 79



More information about the Digitalmars-d mailing list