追加到具有可用空间的字符数组

Appending to a char array that has free space

本文关键字:空间 字符 数组 追加      更新时间:2023-10-16
struct FF{
   void append( char *str ){
         const int strLength = strlen( str );
    const int totalLength = strLength + size;
    char *tmp;
    if( freeSpace < strLength ){
        //not enough free space available for the str to append
        //allocate the total str length including the current size + free space
        tmp = new char[totalLength + 10];
        freeSpace = 10;
        //cpy old string and new string to tmp
        for( int i = 0; i < size; i++ ){
            tmp[i] = strVal[i];
        }
        for( int i = size; i < totalLength; i++ ){
            tmp[i] = str[i];
        }
        delete[] strVal;
        strVal = new char[totalLength+10];
        size = totalLength;
        strcpy( tmp, strVal );
    }else{
        for( int i = size; i <= totalLength; i++ ){
            strVal[i] = str[i];
        }
        freeSpace -= strLength;
        size += strLength;
    }

   }
   char *strVal;      
  unsigned int size;
  unsigned int freeSpace;
};

int main(){
FF a;
a.strVal = new char[10];
a.freeSpace = 10;
a.size = 0;
a.append( "str" ); // should have 7 bytes left
a.append( "len" ); // should have 4 bytes left
std::cout << a.strVal << std::endl; //prints str instead of strlen
return 0;
}

我希望strVal可用空间,这样我就不必每次向其追加内容时都分配空间。但是,第一个附加效果很好。但是当我再次附加它时,它不起作用。所以最后只会打印出str。

问题是,else 子句必须更改为:

...
}else{
    for( int i = 0; i <= strLength; i++ ){
        strVal[i+size] = str[i];
    }
    freeSpace -= strLength;
    size += strLength;
}

你在第二个 for 循环中遇到了问题:
... for( int i = size; i < totalLength; i++ ){ tmp[i] = str[i]; }

索引itmp没问题,但对str不行:
... for( int i = size; i < totalLength; i++ ){ tmp[i] = str[i<b> - size</b>]; }

之后,您无需为strVal分配新的缓冲区并从tmp复制(再次(:只需将tmp分配给strVal
这摆脱了 strcpy((,其中参数的顺序是错误的,如 @doctorlove 所示。

最后,您有一个内存泄漏:您为tmp分配了一个 char 数组,但从未释放它。如果您如上所述更改处理方式,也可以摆脱它。