char* timeNew = _com_util::ConvertBSTRToString(cpi->getTime());
if(timeFirst == true)
{
strcpy(timeOld,timeNew);
timeFirst = false;
}
如果我不知道 cpi->getTime 返回的字符数组的大小是多少,我该如何初始化 timeold?
最佳答案
根据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.
如果确实需要,您可以使用 std::string::c_str()
访问 const char*
。
关于c++ - 正在使用变量 timeOld 而未在 C++ 中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9669759/