c++ - 正在使用变量 timeOld 而未在 C++ 中初始化

标签 c++ char

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/

相关文章:

c++ - 使用指针作为返回类型实现模板化接口(interface)的函数 -> 冲突返回类型错误

c++ - Boost 1.56 with QT creator, "LNK1104: cannot open file ' libboost_unit_test_framework-vc100-mt-gd-1_56.lib'”

c++ - 从 C++ 中的 .txt 文件读取多行

c++ - 在 C++ 中将字符数组从索引 i 转换为字符串 j

c++ - 由于 if 语句 c++11 而避免重复代码的不便

c++ - 在Linux中查询RTC和NTP时间?

c# - 有没有办法将字符串与 char 作为 const 连接?

c++ - 在 Char 数组中测试 nullptr (C++)

将 char* 转换为 unsigned char*

在C中将两个整数连接成一个char *