I'd like to know how to get an array rows & columns size. For instance it would be something like this:
int matrix[][] = { { 2, 3 , 4}, { 1, 5, 3 } }
The size of this one would be 2 x 3. How can I calculate this without including other libraries but stdio or stdlib?
int A[15]; then A has physical size 15. The logical size of an array is the total number of occupied slots. It must be less than or equal to the physical size.
To find the length of an array in Python, we can use the len() function. It is a built-in Python method that takes an array as an argument and returns the number of elements in the array. The len() function returns the size of an array.
This has some fairly limited use, but it's possible to do so with sizeof
.
sizeof(matrix) = 24 // 2 * 3 ints (each int is sizeof 4)
sizeof(matrix[0]) = 12 // 3 ints
sizeof(matrix[0][0]) = 4 // 1 int
So,
int num_rows = sizeof(matrix) / sizeof(matrix[0]);
int num_cols = sizeof(matrix[0]) / sizeof(matrix[0][0]);
Or define your own macro:
#define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
int num_rows = ARRAYSIZE(matrix);
int num_cols = ARRAYSIZE(matrix[0]);
Or even:
#define NUM_ROWS(a) ARRAYSIZE(a)
int num_rows = NUM_ROWS(matrix);
#define NUM_COLS(a) ARRAYSIZE(a[0])
int num_cols = NUM_COLS(matrix);
But, be aware that you can't pass around this int[][]
matrix and then use the macro trick. Unfortunately, unlike higher level languages (java, python), this extra information isn't passed around with the array (you would need a struct, or a class in c++). The matrix
variable simply points to a block of memory where the matrix lives.
If 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