2D string array as parameter to function
Jun 15, 2012 at 11:39am UTC
Hi,
Is it possible to pass a 2D dynamic string array to a function as a parameter?
For.Ex:
1 2 3 4 5 6 7 8 9
string stringArray2D[1][4]= {"Hello" , "How" , "Are" , "You" };
string stringArray2D[1][3]= {"Hello" , "How" , "Are};
process2DStringArray(stringArray2D);
void process2DStringArray(string stringArray2D[][])
{
}
How can I make the parameter to take a generalised any size of 2D string array?
Thank you!
Jun 15, 2012 at 11:59am UTC
I do not see any sense in the constructions
1 2
string stringArray2D[1][4]= {"Hello" , "How" , "Are" , "You" };
string stringArray2D[1][3]= {"Hello" , "How" , "Are};
Why do you not use simply
1 2
string stringArray2D[4]= {"Hello" , "How" , "Are" , "You" };
string stringArray2D[3]= {"Hello" , "How" , "Are};
As for your question string stringArray2D[1][4] and string stringArray2D[1][3] are two different types. So you can not use one function with the same parameter. You can write a template function as for example
1 2 3 4 5
template <size_t N>
void process2DStringArray( std::string ( *stringArray2D )[N], size_t m )
{
/* some code */
}
Or instead of a two-dimensional array you can use std::vector. For example
std::vector<std::vector<std::string>> v;
Last edited on Jun 15, 2012 at 12:52pm UTC
Jun 15, 2012 at 12:22pm UTC
Ohh sorry! That's just a wrong ex.
I wanted to use multidimentional arrays as below
1 2
string stringArray2D[2][4]= {"Hello" , "How" , "Are" , "You" , "I" , "am" , "fine" , "ty" };
string stringArray2D[3][3]= {"Hello" , "How" , "Are" , "good" , "fine" , "nice" , "notGood" , "NotFine" , "NotNice" };
Jun 15, 2012 at 12:44pm UTC
As I said in this case you should write a template function similar to that I showed.
Or it would be much better to use a vector. I will show you an example. It will not be compiled by MS VC++ but will be compiled with GCC 4.7.0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<std::string>> v =
{ { "one" , "two" , "three" } };
for ( const auto &x : v )
{
for ( const auto &s : x )
{
std::cout << s << ' ' ;
}
}
std::cout << std::endl;
}
Last edited on Jun 15, 2012 at 12:49pm UTC
Jun 15, 2012 at 12:56pm UTC
Thank you for suggestion and example too.
I use MS VC++ .. I will go with the first option :)
Thank you again!!
Topic archived. No new replies allowed.