【发布时间】:2016-01-23 23:37:26
【问题描述】:
我的最后一个功能不起作用。此函数将文字字符串附加到 C 字符串。它检查 C 字符串中是否有足够的空间来附加文字字符串。如果没有足够的空间,则必须将 C 字符串长度扩展为(字面字符串长度 + C 字符串长度)的两倍大小。然后它可以将文字字符串附加到 C 字符串中。在我运行程序并输入文本字符串后,会显示第一个输出语句,然后在我不断收到“在抛出 std::bad_alloc 的实例后调用终止”错误并且程序停止工作之后。所有其他功能在此附加功能之前工作。有没有办法修复最后一个附加功能工作?
int main()
{
char* s1 = assign();
char* s2 = assign(" C++ ");
char* s3 = add(s1, s2);
cout << "length of \"" << s3 << "\" is " << strlen(s3) << endl;
append(s3, "programming language"); // This function doesn't work
cout << "length of \"" << s3 << "\" is " << strlen(s3) << endl;
return 0;
}
char* assign()
{
const int SIZE = 100;
char temp[SIZE];
int length;
int twicelen;
cout << "Enter a text string which will be used to append literal strings to it: ";
cin.getline(temp, SIZE);
length = strlen(temp);
twicelen = length * 2;
char* newCstring = new char[twicelen];
strcpy(newCstring, temp);
return newCstring;
}
char* assign(string str)
{
int len = strlen(str.c_str());
int newlen = len * 2;
char* newStr = new char[newlen];
strcpy(newStr, str.c_str());;
return newStr;
}
char* add(char* s1, char* s2)
{
strcat(s1, s2);
return s1;
}
void append(char* s3, string literalStr) // Every function before this works and this is where the program gives an error and closes.
{
if (sizeof(s3) < (strlen(s3) + strlen(literalStr.c_str()) + 1))
{
int expandLength = (strlen(s3) + strlen(literalStr.c_str())) * 2;
char* s3 = new char[expandLength];
strcat(s3, literalStr.c_str());
}
else
strcat(s3, literalStr.c_str());
}
【问题讨论】:
-
你为什么不用std::string?
-
你在学习指针吗?因为否则你应该使用
std::string。 -
添加一些输出以显示
sizeof(s3)的值。这不是你想的那样。 -
sizeof(s3) 可能返回 1,因为它获取指针的大小。我不确定你会在那条线上实现什么
-
@Pooya - 它几乎肯定不会是 1。那将是一个相当不寻常的架构。也许是一些 DSP,但不是主流计算机。
标签: c++ string function pointers c-strings