Squaring Arrays without Overlapping Array Error

tcak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 7 01:06:48 PDT 2015


On Tuesday, 7 July 2015 at 05:27:10 UTC, jmh530 wrote:
> If I call a function like
>
> int[] square_array(int[] x)
> {
> 	return x[] *= x[];
> }
>
> I get an error that there is an overlapping array in a vector 
> operation. I guess this makes sense as the lhs and rhs are 
> occupying the same memory. Nevertheless, I find it a little 
> frustrating.
>
> I tried two alternatives, one just adds a temporary duplicate 
> array for the lhs x[] in the above, while the other uses a 
> foreach loop. Both get correct results without errors, but also 
> have their issues. Duplicating requires memory allocation, 
> which makes it slower for small arrays. Foreach (ignoring 
> parallelism or SIMD) tends to be slower for larger arrays, I 
> take it due to compiler optimizations for vector operations.
>
> Are there any other alternatives here?

I have never used arrays in that way before, though I don't get 
why you are writing return line in that way. Shouldn't it be like 
`return (x[] * x[]);` ?


More information about the Digitalmars-d-learn mailing list