Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array size

Tags:

arrays

c

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?

like image 311
John Doe Avatar asked May 27 '10 04:05

John Doe


People also ask

What is the size of an array?

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.

How do you get a size of an array Python?

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.


1 Answers

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.

like image 76
Stephen Avatar answered Oct 08 '22 19:10

Stephen