seamoon wrote in news:d0**********@news.hananet.net in comp.lang.c++:
How can I use 2 dimension of array instead of using pointer
array, in the following exmples.
I treated pointer variable in SSetDlg structuer as [n][50]
array. But I think that there's an exact method to use the
2 dimension pointer array in the SSetDlg structure.
For example, the same as like struct SSetDlg { char *c[]; }.
Give me your advice please.
#include <iostream>
#include <ostream>
#include <cstring>
struct SSetDlg
{
char (* const szNameList)[ 50 ];
SSetDlg( std::size_t n ) : szNameList( new char[n][50] )
{
for ( std::size_t i = 0; i < n; ++i )
{
std::memset( szNameList[i], 0, sizeof( szNameList[i] ) );
}
}
~SSetDlg()
{
delete [] szNameList;
}
private:
SSetDlg( SSetDlg const & ); /* prevent copying */
};
void CSetDlg_OnSet()
{
int n = 10;
SSetDlg stSetDlg( n );
for ( std::size_t i = 0; i < n; ++i )
{
std::strncpy(
stSetDlg.szNameList[ i ], "sample", sizeof( stSetDlg.szNameList[0] )
);
}
for ( std::size_t i = 0; i < n; ++i )
{
std::cout << stSetDlg.szNameList[ i ] << '\n';
}
std::cout.flush();
}
int main()
{
CSetDlg_OnSet();
}
Hopefully the above answers your question about array's. The
parenthesis are required as otherwise you get an array of 50
pointers not a pointer to an array of 50 char.
Here's a different approach using std::vector<>, it uses more free
store (heap) but that shouldn't matter here.
It has the advantage that SSetDlg is now coypable and assignable plus
there is nolonger any need to manage the new [] and delete [] calls.
#include <iostream>
#include <ostream>
#include <vector>
struct SSetDlg
{
std::vector< std::vector<char> > szNameList;
SSetDlg( std::size_t n ) : szNameList( n, std::vector<char>(50) )
{
}
};
void CSetDlg_OnSet()
{
int n = 10;
SSetDlg stSetDlg( n );
for ( std::size_t i = 0; i < n; ++i )
{
std::strncpy(
&stSetDlg.szNameList[ i ][0], "sample",
stSetDlg.szNameList[ i ].size()
);
}
for ( std::size_t i = 0; i < n; ++i )
{
std::cout << &stSetDlg.szNameList[ i ][0] << '\n';
}
std::cout.flush();
}
int main()
{
CSetDlg_OnSet();
}
Rob.
--
http://www.victim-prime.dsl.pipex.com/