6

I want to create 3-dimensional array in ocaml. Here's what I tried to do:

let dp = Array.make n (Array.make n (Array.make k (-1))

However it doesn't work - changing a value dp[0][0][0] changes all values dp[i][j][0]. So how to create matrix with distinct arrays, not with copies of the same one?

qiubit
  • 4,708
  • 6
  • 23
  • 37
  • 1
    Look at : http://caml.inria.fr/resources/doc/faq/core.en.html. Quoting this url : The allocation of a new array has two phases. First, the initial value is computed; then this value is written in each element of the new array. That's why the line which is allocated by Array.make 3 0 is unique and physically shared by all the lines of the array m. – Pierre G. Jan 19 '15 at 20:34

1 Answers1

11

Array.make n v will just replicate the second argument n times. In other words, it will assign it in a cycle to each element. Since arrays (as well as all other heap-allocated values) are passed by reference, all cells will point to the same array. You need to use the Array.init function, that will call user provided function for each element:

let dp = Array.init n (fun _ -> Array.init n (fun _ -> (Array.make k 0)))

But, for real multidimensional numeric code, you shouldn't use arrays, but instead use Bigarray module. Here is the example:

open Bigarray
let dp = Array3.create int c_layout 3 3 3
dp.{0,0,0} <- 1
ivg
  • 34,431
  • 2
  • 35
  • 63