Static Arrays: Behaviour of Passing & Returning

Quantum Nerd qnerd at posteo.org
Wed Mar 21 12:01:01 UTC 2018


Hello everybody,

I am fairly new to the D language,
and I've been trying to understand the behaviour
of passing arrays to functions, especially also
static arrays.

There is an example that puzzles me:

import std.stdio;

double[3] sqr( double[3] v ) {
   double[3] r;
   writefln( "v (%20s) : %s", typeof(v).stringof, &v[0] );
   writefln( "r (%20s) : %s", typeof(r).stringof, &r[0] );
   r[] = v[] * v[];
   return r;
}

void main() {
   double[3] a = [1.0, 2.0, 3.0 ];
   double[3] b = sqr(a);
   writefln( "a (%20s) : %s", typeof(a).stringof, &a[0] );
   writefln( "b (%20s) : %s", typeof(b).stringof, &b[0] );

   double[3] c; c = sqr(a);
   writefln( "c (%20s) : %s", typeof(c).stringof, &c[0] );
}


with the output:
v (           double[3]) : 7FFD0D3874E0
r (           double[3]) : 7FFD0D387548
a (           double[3]) : 7FFD0D387528
b (           double[3]) : 7FFD0D387548
v (           double[3]) : 7FFD0D3874E0
r (           double[3]) : 7FFD0D387588
c (           double[3]) : 7FFD0D387568


According to the documentation, static arrays are of value type.

How is it possible that b in main() and r in the function occupy 
the same memory?
I would expect the same behaviour as with c.

Can somebody with more experience shed some light on this?


Thanks in advance,

qnerd





More information about the Digitalmars-d-learn mailing list