question regard 2d array

hi,

How can if find what is the number of the rows in a 2 dimention array?

Thank you,
Daniel
By looking at the code where it is created and reading the numbers.
so if for example I do:

const char forbiddenStrings[][SIZE] = {"flower", "blo", "plant", ""};

so how can I calculat the rows number of it? (not manually)

strlen doesnt works here....
All elements of the array (that is rows) have the same size that is SIZE.

The number of rows is calculated the following way

size_t Rows = sizeof( forbiddenStrings ) / sizeof( *forbiddenStrings );

In your case the formula is equivalent to

size_t Rows = sizeof( forbiddenStrings ) / SIZE;


Another way is to write two template functions

1
2
3
4
5
6
7
8
9
10
11
template <typename T, size_t N, size_t M>
inline size_t Rows( T ( &a )[N][M] )
{
   return ( N );
}

template <typename T, size_t N, size_t M>
inline size_t Cols( T ( &a )[N][M] )
{
   return ( M );
}


And in your code use

1
2
size_t n = Rows( forbiddenStrings );
size_t m = Cols( forbiddenStrings );
Last edited on
Thank you very much!!!!

you helped me a lot.
Topic archived. No new replies allowed.