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()

10-04 12:36