2012-03-12 7 views
0
char* timeNew = _com_util::ConvertBSTRToString(cpi->getTime()); 
if(timeFirst == true) 
    { 
    strcpy(timeOld,timeNew); 
    timeFirst = false; 
    } 

cpi-> getTimeによって返される文字配列のサイズがわからない場合、どのようにinitoldを初期化できますか?変数timeOldがC++で初期化されずに使用されています

+0

'if(timeFirst == true)'?うん! –

+0

そのグローバルブール –

+1

'if(timeFirst)'を推奨します。テキスト '== true'は不要で冗長です。そして冗長。 –

答えて

1

timeNewの長さに基づいて、それのためにメモリを割り当てます。

delete[] timeOld; 
timeOld = new char[strlen(timeNew) + 1]; 

か、timeOldstd::stringを作り、それはあなたのためにメモリを管理しましょうことができます:

std::string timeOld; 

timeOld = timeNew; // If timeNew is dynamically allocated you must still 
        // delete[] it when no longer required, as timeOld 
        // takes a copy of timeNew, not ownership of timeNew. 

あなたはstd::string::c_str()を使用してconst char*にアクセスすることができます本当に必要ならば。

1

使用文字列可能な場合:あなたは、単にtehの関数によって返されたメモリを管理する必要がない場合は

char *t= _com_util::ConvertBSTRToString(cpi->getTime()); 
std::string timeNew(t); 
delete[] t; 
if(timeFirst == true) 
{ 
    timeOld=timeNew; 
    timeFirst = false; 
} 

:あなたはConvertBSTRToStringを使用する必要がある場合

std::string timeNew(_com_util::ConvertBSTRToString(cpi->getTime())); 
if(timeFirst == true) 
{ 
    timeOld=timeNew; 
    timeFirst = false; 
} 
0

その後、使用boost::scoped_array<char>またはboost::shared_array<char>あなたがきれいになるように。

boost::shared_array<char> time; 
time.reset(_com_util::ConvertBSTRtoString(cpi->getTime()); 

が自動的に再割り当てされます。 []を削除または削除する呼び出しは必要ありません。

関連する問題