追加到具有可用空间的字符数组
Appending to a char array that has free space
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];
}
索引i
对tmp
没问题,但对str
不行:
...
for( int i = size; i < totalLength; i++ ){
tmp[i] = str[i<b> - size</b>];
}
之后,您无需为strVal
分配新的缓冲区并从tmp
复制(再次(:只需将tmp
分配给strVal
。
这摆脱了 strcpy((,其中参数的顺序是错误的,如 @doctorlove 所示。
最后,您有一个内存泄漏:您为tmp
分配了一个 char 数组,但从未释放它。如果您如上所述更改处理方式,也可以摆脱它。
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 命名空间中具有.h和.cpp文件的类
- 为什么 Serial.println(<char[]>);返回随机字符?
- 打印第二列时的2d字符矢量打印空间
- 如何为结构字段动态分配字符空间
- 空间字符函数
- 如何定义一个从任何编码空间解析单个字符的精神 x3 解析器?
- 识别C 程序中的空间字符
- 在线路中的字符之前卸下所有空间
- 是ASCII字符255隐形字符或空间
- 将两次使用的字符放在变量中是空间的增益
- 追加到具有可用空间的字符数组
- 如何将字符串的三个字符放入数组的一个空间中
- 从高效方法中删除指定的字符(时间和空间复杂性)
- 如何从字符变量中删除空白空间
- 是否存在编解码场景,其中目标缓冲区需要多个内部字符的空间
- 将用户输入的空间存储在字符数组中
- 为什么一个字符在数组中似乎比它本身占用更多的空间