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.
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.
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