Help with 2d arrays

Hi all,

I was wondering how you would call a function that works with 1d arrays on a 2d array.

For example:

char word [30][20000];

The 30 corresponds to the letter and the 20000 corresponds to the word (which is part of a list of words)

How would I use this array with something like strcmp (otherword,word[][])? I don't want to compare it one letter at a time, I want to compare one word in the list to a different 1 dimensional string.
For example you can use the for statement based on range

1
2
3
4
for ( const auto &x : word )
{
   if ( std::strcmp( x, "Some word" ) == 0 ) std::cout << x << std::endl;
} 


In other words word[ i ] (where i is an arbitrary number in the range 0-29) will give you a required word in the array.
Last edited on
I'm sorry I'm a bit new to c++, what does the for loop you created do? (I know about for loops but I don't understand the conditions in that one)

Thanks
Ryan
It is so-called the range-based for statement. It uses iterators of the specified container to travers all elements in the container. This loop

1
2
3
4
for ( const auto &x : word )
{
   if ( std::strcmp( x, "Some word" ) == 0 ) std::cout << x << std::endl;
}


is equivalent to

1
2
3
4
for ( char ( *ip )[20000] = std::begin( word ); ip != std::end( word ); ++ip )
{
   if ( std::strcmp( *ip, "Some word" ) == 0 ) std::cout << *ip << std::endl;
}


Or that to be more clear for you it can be written as

1
2
3
4
for ( size_t i = 0; i < 30; i++ )
{
   if ( std::strcmp( word[i], "Some word" ) == 0 ) std::cout << word[i] << std::endl;
}
Last edited on
thanks very much... how does that work? I noticed you have only 1 dimension of the array refrenced in strcmp and cout... how does the computer know which dimension that is?

I was reading something about that but I was never able to find anything too in depth.

Thanks so much,
Ryan
ward[i] is a character array. For character arrays there is an overloaded operator << in C++.
So that means we are allowed to omit the last index like this right?

1
2
word  [i][a];
cout << word [i];
A multidimensional array with n dimensions is an array of arrays of [n-1] dimensions. That is the element of a multidimensional array with n dimensions is an array with n-1 dimensions.
Topic archived. No new replies allowed.