【发布时间】:2015-10-22 19:27:44
【问题描述】:
这是我的代码的一部分:
for(int i=0; i<10; i++)
{
tab[i]=new char[80];
oss.str("");
oss<<"line number: <<i;
temp=oss.str();
tab[i]=(char*)temp.c_str();
}
当我打印标签时,结果是轮流 8 和 9。我做错了什么吗?
【问题讨论】:
-
你确定吗?因为这甚至不应该编译。请发帖minimal reproducible example
-
(char*)temp.c_str()坏主意!修改tab[i][x]现在会调用未定义的行为。此外,您还泄漏了newed 数组,仅比其分配低 4 行... -
如果
tab[i]=(char*)temp.c_str();的意思是将temp的内容复制到tab[i],那就不行了;你只是重新指向指针。您首先需要使用strncpy,或者更好的是std::string。 -
Temp 是一个字符串对象。我使用 char 数组而不是字符串,因为它只是练习数组和指针的练习。如何以其他方式将 c-string 分配给 char*?
-
您的意思可能是
strcpy(tab[i], temp.c_str());。正如您所拥有的,tab[i]指向内部管理的temp字符串,因此稍后当您重新分配temp(下一次循环迭代)时,前一个tab[i]将成为悬空指针
标签: c++ stringstream ostringstream