我的追加函数没有像预期的那样工作.c++

My append function does not work as expected. C++

本文关键字:工作 c++ 函数 追加 我的      更新时间:2023-10-16

我正在编写自己的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,忘记所有这些问题。