The best I've found
Preserves the size attributes of the matrix array (although not from the matrix list) and allows you to use your own indexing notation
int n=5, T=2; float (*a)[n][n] = calloc(T,sizeof(float[n][n])); // <== initializes to 0! for (size_t t=0; t<T; ++t) for (size_t i=0; i<n; ++i) a[t][i][i] = 1.0; // <== only set the 1's
Declaring a pointer to 2d arrays is the hard part, but calloc (see below) takes care of zero initialization for you, so you only set non-zero elements.
Of course, the fun part comes when you try to convey these things ... but if you are careful about your declaration and use c99, you can do any of
void foo(int n, float (*a)[n][n]) { // ... } void bar(int t, int n, float a[t][n][n]) { // ... }
Job. (Actually gcc will let you go if you don't use -std=c89 -pendantic ...)
Best of all, but it will work with ansi-c
You can, of course, simplify reading the traditional version (with ugly manual indexing).
int n = compute_size_of_matrices(); int T = compute_number_of_matrices(); float* matrices = calloc(T, sizeof(float) * n*n);
Well, that seemed like a good idea ...
Alas, c won't let you do
int n=5, T=2; float matrices[T][n][n] = {}; // <== ***ERROR!!!***
which will allow you to maintain the "massiveness" of the matrices and be even more clear.
Is he slow?
Since calloc will use some highly optimized write to system memory to set to 0, you will not be hit hard by speed.
source share