【问题标题】:My append function does not work as expected. C++我的附加功能没有按预期工作。 C++
【发布时间】:2013-04-28 01:29:21
【问题描述】:

我正在编写自己的追加函数,使用静态字符缓冲区 [50] 将字符串数组 2 的动态字符数组追加到字符串数组 1 的另一个动态字符数组的末尾。但是编译器会产生以下错误:[Error] incompatible types in assignment of 'char' to 'char[50]'。我试图找出问题所在,但我似乎没有找到解决方案。您的帮助将不胜感激。我正在使用 Dev-C++。代码如下。

#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;
}

【问题讨论】:

  • 好的,但为什么不使用operator += 代替std::strings?
  • 重新实现字符串类及其成员是学习低级语言(如 C 或 C++)的常用方法。我不认为指出所描述的任务有一个操作员以消除问题的相关性。

标签: c++ arrays function dynamic append


【解决方案1】:

你不能分配到一个数组中,这是你在buffer=*a++ 中所做的。你的意思可能是

static char buffer[50];
char *p=buffer;
*p=*a++;

另外,这里

p--;
while(*p++=*b++);

您正试图在数组开头 前一个元素取消对指针的引用 - 这会导致未定义的行为。

此外,您不会在任何地方检查字符串的长度,因此很容易超过 49 个字符串,您的代码将既不正确也不安全(buffer overflow 攻击的容易受害者)。

最后一个问题是,由于使用了static 数组,您的代码在任何情况下都是不可重入的。如果您不想将其调整为字符串的长度,或者按照此处的建议动态分配它,您可以简单地使用简单的数组。

最好的解决方案当然是使用std::string 并忘记所有这些问题。

【讨论】:

    【解决方案2】:

    您的 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的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多