How to get the size of an array

I would like to know how to get the size of the rows and columns of an array. For example, it would be something like this:

int matrix[][] = { { 2, 3 , 4}, { 1, 5, 3 } }

The size of this will be 2 x 3. How can I calculate this without including other libraries, but stdio or stdlib?

+5
source share
4 answers

This is a fairly limited use, but it is possible with help 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);

, , int[][], . , (java, python) ( ++). matrix , .

+10

"- ". , ( ) [][], C.

, . . 3

int matrix[][3] = { { 2, 3, 4 }, { 1, 5, 3 } };

, 3. 5,

int matrix[][5] = { { 2, 3, 4 }, { 1, 5, 3 } };

, "" , . . , "" - ,

sizeof *matrix / sizeof **matrix

,

sizeof matrix / sizeof *matrix
+5

sizeof (matrix)will give you the total size of the array in bytes. sizeof (matrix[0]) / sizeof (matrix[0][0])gives the size of the internal array, and sizeof (matrix) / sizeof (matrix[0])should be the external size.

0
source

Example for size:

#include <stdio.h>
#include <conio.h>
int array[6]= { 1, 2, 3, 4, 5, 6 };
void main() {
  clrscr();
  int len=sizeof(array)/sizeof(int);
  printf("Length Of Array=%d", len);
  getch();
}
0
source

All Articles