Disallow arrays as pointers

Jonathan M Davis jmdavisProg at gmx.com
Sun Oct 30 14:46:36 PDT 2011


On Sunday, October 30, 2011 17:29:36 bearophile wrote:
> I have translated C code similar to:
> 
> 
> something foo(int n) {
>     int *array = malloc(n * sizeof(int));
> 
>     int i;
>     for (...) {
>         for (i = 0; i < n; i++, array++) {
>             *array = ...;
>             *array = ...;
>         }
>     ...
> }
> 
> 
> Into D2 code similar to:
> 
> 
> something foo(int n) {
>     auto array = new int[n];
> 
>     size_t index;
>     foreach (...) {
>         foreach (i; 0 .. n) {
>             array[index] = ...;
>             *array = ...;
>             index++;
>         }
>     ...
> }
> 
> 
> Do you see the bug I have found during the debugging?
> 
> I think the D2 compiler has to catch this bug:
> 
> *array = ...;
> 
> D arrays aren't pointers. Letting the compiler see them as pointers is
> bug-prone, not tidy, and doesn't help D newbies understand how D represents
> its arrays.
> 
> 
> My bug report:
> http://d.puremagic.com/issues/show_bug.cgi?id=3990
> 
> 
> Some very good comments about this topic:
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&ar
> ticle_id=135391

Arrays in D implicitly convert to their ptr property, so they essentially 
_are_ pointers in that sense. Now, personally, I think that it would be a good 
idea for them _not_ to implicitly convert, forcing you to explicitly use the 
ptr property, since you really shouldn't be treating arrays as pointers in D 
code. It's primarily when interacting with C code that you need to do that 
sort of thing, and the ptr property deals with it just fine.

However, I don't think that you're going to find a general consensus that the 
implicit conversion is bad, and changing it now would likely break a lot of 
code. So, while I do think that it would be a good change, I really don't 
think that it's going to happen at this point.

- Jonathan M Davis


More information about the Digitalmars-d mailing list