Home > OS >  Setting values in 2D Arrays
Setting values in 2D Arrays

Time:11-06

When trying to set a value in a 2D array like this:

let a = Array.make  5 (Array.make 5 0);;
a.(0).(0) <- 4;

It will for some reason put 4 at index j in every array contained in the 2D array a.

Why is this, and how do i get it to only set a[i][j] to 4?

CodePudding user response:

The problem is with how you initialize the matrix. You're creating one inner array that is then assigned to every cell of the outer array instead of creating a new array for each cell. What you're doing is equivalent to this:

let inner = Array.make 5 0 in
let outer = Array.make 5 inner in
inner.(0) <- 4

You could use Array.init to create the outer array instead, which behaves exactly like Array.make except it takes an initialization function instead of the value to insert directly:

Array.init 5 (fun _ -> Array.make 5 0)

But even more convenient for creating a 2-dimensional array is Array.make_matrix:

Array.make_matrix 5 5 0;;

CodePudding user response:

As an addendum to glennsl's answer, you will see this issue anytime you store a mutable value in an array.

Consider:

let arr =
  let x = ref 5 in
  Array.make 5 x

If we assign a new value to that int ref value with arr.(1) := 7 or arr.(0).contents <- 7, arr` is now:

[|{contents = 7}; {contents = 7}; {contents = 7}; 
  {contents = 7}; {contents = 7}|]

The same does not apply if we fill our array with immutable data.

let arr = 
  let x = 5 in
  Array.make 5 x

Now if we update with arr.(0) <- 7, arr is:

[|7; 5; 5; 5; 5|]
  • Related