I want to construct a 2d array in C where each row will have different number of elements. Specifically I want to construct a triangular 7x6 array. In order to save memory I want to avoid storing the zeros as in the following example.
1 0 0 0 0 0 0
1 1 0 0 0 0 0
...
1 1 1 1 1 1 1
How can I do this?
Won't this system of indexing work?
0
1 2
3 4 5
6 7 8 9
...
Just store your data in a single-dimensional array, using this mapping to the triangular matrix/array.
One-dimensional zero-based index k and two-dimensional zero-based row i and column j are the same when k = i(i+1)/2 + j (where j <= i).
The above is for a lower-triangular square matrix/array. You could do something very similar for
i and jIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With