Can you fix this code to avoid using pointers?

XavierAP via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 13 10:19:07 PDT 2017


On Monday, 13 March 2017 at 14:47:20 UTC, H. S. Teoh wrote:
> On Sat, Mar 11, 2017 at 08:07:39PM +0000, XavierAP via 
> Digitalmars-d-learn wrote: [...]
>> But I still like the version with pointers ;)
>
> There's nothing wrong with using pointers in D.  The fact that 
> D alleviates most cases of (explicit) pointers is a testament 
> to just how awesome it is. ;-)  But that shouldn't deter anyone 
> from using (explicit) pointers once in a while.  In fact, D 
> makes it such that it's a lot safer using pointers than in 
> C/C++, mainly because it alleviates most of the dangerous use 
> cases for pointers so what's left is generally harmless stuff. 
> Unless your code for whatever reason is involved in heavy 
> pointer hackery (like OS writing), but that's not a typical use 
> case.

I did it again ;)

enum params = [
	"Radius of disk in m",
	"Integration step size along radius",
	"Total integration time in s",
	"Integration step size along time",
	"Time step size for output",
	"Initial temperature in C",
	"Edge temperature in C",
	"Flow temperature in C",
	"2D conductivity in W K^-1",
	"2D diffusivity in m^2 s^-1",
	"Convective coefficient in W m^-2 K^-1" ];
	
real*[params.length] vals = [
	&R, &dr, &T, &dt, &dtOut,
	&u0, &uc, &ug,
	&k, &a, &h ];

import std.conv: to;

/* ... */

foreach(i, param; params)
{
	/* ... */
	*vals[i] = to!real(val);
}

I had the same requirement to make separate named scalars instead 
of an array; but also an array was handier to assign the values 
inside a loop; and I needed a readable  and simple way to map 
between them. An array of pointers is perfect I think.

And the only dangerous thing I could do with the pointers is 
arithmetic on them instead of the pointed values, but: "pointer 
arithmetic not allowed in @safe functions." So all is good :)


More information about the Digitalmars-d-learn mailing list