A Comparison of Dynamic 3d Array Instantiation in Selected Languages
Python#
matrix = [[[0 for _ in range(l)] for _ in range(m)] for _ in range(n)]
Java#
int[][][] matrix = new int[n][m][l];
Haskell#
matrix = replicate n (replicate m (replicate l 0))
OCaml#
let matrix = Array.init n (fun _ -> Array.init m (fun _ -> Array.make l 0))
C++11#
#include <vector>
std::vector<std::vector<std::vector<int>>> matrix(n,
std::vector<std::vector<int>>(m,
std::vector<int>(l)));
C99 (VLA)#
#include <stdlib.h>
int (*matrix)[m][l] = malloc(sizeof(int[n][m][l]));
C89#
#include <stdlib.h>
int ***matrix;
int i, j;
matrix = malloc(n * sizeof(int **));
for (i = 0; i < n; i++) {
matrix[i] = malloc(m * sizeof(int *));
for (j = 0; j < m; j++) {
matrix[i][j] = calloc(l, sizeof(int));
}
}
Read other posts