How to find 2D array (matrix) size (rows, cols) in C

2 Answers

0 votes
#include <stdio.h>
 
int main()
{
    int matrix[][4] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 } };
     
    int rows = sizeof(matrix) / sizeof(matrix[0]);
    int cols = sizeof(matrix[0]) / sizeof(matrix[0][0]);
  
    printf("rows = %d\n", rows);
    printf("cols = %d\n", cols);
    printf("total cells = %d\n", rows * cols);
    
    return 0;
}
  
   
/*
run:
   
rows = 3
cols = 4
total cells = 12
   
*/

 



answered May 24, 2017 by avibootz
edited Oct 1, 2025 by avibootz
0 votes
#include <stdio.h>

#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))

int main(int argc, char **argv)
{
    int matrix[][4] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 } };
    
    int rows = ARRAYSIZE(matrix);
    int cols = ARRAYSIZE(matrix[0]);
 
    printf("rows = %d\n", rows);
    printf("cols = %d\n", cols);
   
    return 0;
}
 
  
/*
run:
  
rows = 3
cols = 4
  
*/

 



answered May 24, 2017 by avibootz
...