Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of rows and columns in a 2D array in C (any simpler way than this?)

Tags:

c

I have this code fragment:

    char result[10][7] = {
        {'1', 'X', '2', 'X', '2', '1', '1'},
        {'X', '1', '1', '2', '2', '1', '1'},
        {'X', '1', '1', '2', '2', '1', '1'},
        {'1', 'X', '2', 'X', '2', '2', '2'},
        {'1', 'X', '1', 'X', '1', 'X', '2'},
        {'1', 'X', '2', 'X', '2', '1', '1'},
        {'1', 'X', '2', '2', '1', 'X', '1'},
        {'1', 'X', '2', 'X', '2', '1', 'X'},
        {'1', '1', '1', 'X', '2', '2', '1'},
        {'1', 'X', '2', 'X', '2', '1', '1'}

    };

    int row = sizeof(result) / sizeof(result[0]);
    int column = sizeof(result) / row;

    printf("Number of rows: %d\n", row);
    printf("Number of columns: %d\n", column);

is there any prebuilt function or anything like that especially for calculating number of columns? I am asking this because we get the number of total elements as sizeof(arr) / sizeof(int) and need another division, but I want to compute the number of columns directly.

like image 464
Infected-Øne Avatar asked Nov 02 '25 03:11

Infected-Øne


1 Answers

To compute the number of elements of any defined array, you can use the sizeof operator regardless of the array element type:

some_type A[] = { ... };
size_t length = sizeof(A) / sizeof(A[0]);

For your 2D array definition, you can get the number of columns as the length of array result[0].

Here is a modified version of your code to get the lengths of both dimensions directly:

#include <stdio.h>

int main() {
    char result[][7] = {
        {'1', 'X', '2', 'X', '2', '1', '1'},
        {'X', '1', '1', '2', '2', '1', '1'},
        {'X', '1', '1', '2', '2', '1', '1'},
        {'1', 'X', '2', 'X', '2', '2', '2'},
        {'1', 'X', '1', 'X', '1', 'X', '2'},
        {'1', 'X', '2', 'X', '2', '1', '1'},
        {'1', 'X', '2', '2', '1', 'X', '1'},
        {'1', 'X', '2', 'X', '2', '1', 'X'},
        {'1', '1', '1', 'X', '2', '2', '1'},
        {'1', 'X', '2', 'X', '2', '1', '1'},
    };

    size_t rows = sizeof(result) / sizeof(result[0]);
    size_t cols = sizeof(result[0]) / sizeof(result[0][0]);

    printf("Number of rows: %zu\n", rows);
    printf("Number of columns: %zu\n", cols);
    return 0;
}

Note however that the expressions for row and column in your code are computed at compile time by optimizing compilers.

like image 89
chqrlie Avatar answered Nov 03 '25 17:11

chqrlie