char* timeNew = _com_util::ConvertBSTRToString(cpi->getTime());
if(timeFirst == true)
{
strcpy(timeOld,timeNew);
timeFirst = false;
}
如果我不知道cpi-> getTime返回的字符数组的大小,该如何初始化旧时间?
最佳答案
根据timeNew
的长度为其分配内存:
delete[] timeOld;
timeOld = new char[strlen(timeNew) + 1];
或者您可以将
timeOld
设置为std::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.
如果确实需要,可以使用
const char*
访问std::string::c_str()
。