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;
}
I want the strVal to have free space so I don't have to allocate space everytime I append something to it. However, the first append works just fine. But when I append it another time, it does not work. So at the end only str will be printed out.
std::stringstd::string, it does automatic allocation, and you can just callmyString.reserve(myString.size() + 10);strcpy( tmp, strVal );... which is dest and which is source?