我正在用 c++ 11 构建自己的字符串类,但我遇到了内存问题。
主要:
MyString str1; //Works ok, constructor creates empty char array.
const char* pointer1 = str1.c_str(); //Return the pointer to the array.
str1.Reserve(5);
// Now, when I use the Reverse method in string1, Pointer1 is
// pointing to the old memory address.
如何更改 str1 中的数组数据,但更改为内存地址?
换句话说,我该如何解决这个问题:
pointer1 == str1.c_str();
预约方式:
void reserve(int res)
{
capacity = NewSize(size + res,0 , capacity); //Method to find the best cap.
char* oldData = data;
data = new char[capacity];
memcpy(data, oldData, capacity);
oldData = data;
//delete[] data;
data[(size)] = '\0';
}
这会返回所有正确的数据,但是当我执行“oldData = data”时,内存地址会丢失。
感谢所有帮助,谢谢!