1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <string>
#include <memory>
#include <cstring>
// convert string to c-style string, alocate space for 'extra' chars
// release the allocated memoty with delete[]
char* string_to_cstr( const std::string& str, std::size_t extra = 0 )
{
char* cstr = new char[ str.size() + 1 + extra ] ;
std::uninitialized_copy( str.begin(), str.end(), cstr ) ; // copy chars
cstr[ str.size() ] = 0 ; // null terminate
return cstr ;
}
int main()
{
std::string abcd = "abcd", efg = "efg" ;
char* mad[] = { string_to_cstr(abcd,50), string_to_cstr(efg,25),
string_to_cstr("ijklmnop"), string_to_cstr("qr",10) } ;
for( char* cstr : mad ) std::cout << cstr << '\n' ;
std::cout << '\n' ;
std::strcpy( mad[0], "bigger string (max 54 chars)" ) ;
std::strcpy( mad[1], "hello" ) ;
std::strcpy( mad[2], "world" ) ;
std::strcpy( mad[3], "bye" ) ;
for( char* cstr : mad ) std::cout << cstr << '\n' ;
for( char*& cstr : mad ) { delete[] cstr ; cstr = nullptr ; }
}
|
abcd
efg
ijklmnop
qr
bigger string (max 24 chars)
hello
world
bye |