Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird thing of Array.create in OCaml

I'm a newbie at OCaml. And when I do some coding using array in Ocaml I come to a problem I can't understand.
Here is the code:

let a = Array.create 5 (Array.create 5 0);
a.(0).(1) <- 1

I just want to assign 1 to a[0][1] but then things happened: all the element in the first colummn has been assigned. That is, a[0][1], a[1][1], a[2][1], a[3][1] and a[4][1] are all equal to 1 after the code above executed.
If I create the array using:

Array.make_matrix 5 5 0

everything is fine.

My environment:

Ubuntu 13.10
Ocaml 4.01.0
open Core.Std 
like image 815
KUN Avatar asked Dec 11 '22 09:12

KUN


1 Answers

This is a common pitfall of Array.create. Use Array.init instead when your array element is boxed.

Array.create initializes the array elements with the same value: if the value is boxed, with the same pointer. In your case, all the elements a.(i) points to the same array created by Array.create 5 0.

Correct code should be

let a = Array.init 5 (fun _ -> Array.create 5 0)

This creates 5 individual arrays.

You should check this Q/A: Ocaml - Accessing components in an array of records

like image 118
camlspotter Avatar answered Jan 08 '23 08:01

camlspotter