我的追加函数没有像预期的那样工作.c++
My append function does not work as expected. C++
我正在编写自己的append函数,将字符串array2的动态字符数组附加到字符串array1的另一个动态字符数组的末尾,使用静态字符缓冲区[50]。但是编译器会产生以下错误:将'char'赋值给'char[50]'时,[Error]类型不兼容。我已设法找出这个问题,但似乎找不到解决办法。非常感谢您的帮助。我正在使用devc++。代码如下:
#include <iostream>
using namespace std;
char *Appendstring(char *a, char *b) // will append b to the end of a
{
static char buffer[50];
char *p=buffer=*a++; //[Error] incompatible types in assignment of 'char' to 'char[50]'
//[Error] invalid conversion from 'char*' to 'char'[-fpermissive]
p--;
while(*p++=b++);
p--; //append
while(*p++=*c++);
return buffer;
}
int main ()
{
string str="Displaying: ";
string add=" Summer is coming";
Appendstring(str, add);
return 0;
}
在你的append函数中有多个错误,最大的错误是使用数组作为指针并使用静态缓冲区合并字符串。有了静态缓冲区,所有合并的字符串都将在同一个空间中,因此合并两个字符串,然后合并另外两个字符串将覆盖第一个合并的结果!
你可以这样修改你的函数:
char *Appendstring(const char *a, const char *b) // will append b to the end of a
{
char *buffer = new char[strlen(a)+strlen(b)+1];
char *p=buffer;
while(*p++=*a++); // Copy a into buffer
while(*p++=*b++); // Copy b into buffer right after a
*p=0; // Null-terminate the string
return buffer;
}
当然现在调用方负责释放Appendstring
的结果
你不能赋值到一个数组中,这是你在buffer=*a++
中所做的。你的意思可能是
static char buffer[50];
char *p=buffer;
*p=*a++;
另外,这里
p--;
while(*p++=*b++);
试图在数组开头的元素前解除对指针的保护,这会导致未定义的行为。
此外,没有任何地方检查字符串的长度,因此很容易超过49个字符串,您的代码将既不正确又不安全(容易成为缓冲区溢出攻击的受害者)。
最后一个问题是,你的代码是不可重入的任何方式,由于使用static
数组。您可以简单地使用简单数组,如果你不想调整它的字符串的长度,或动态分配它,如这里所建议的。
最好的解决方案当然是使用std::string
,忘记所有这些问题。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 为什么stream::忽略未按预期工作