我正在为自己编写一个动态数组,我希望它预设为零。
简单来说,我们会将数据重新分配到索引+1的位置,并将未清零的内存设为0。
关于测试,我首先在这个数组的第5个位置插入了数字5。预期的结果发生了——
template <class T>
dynArr<T>::dynArr()
{
rawData = malloc(sizeof(T) * 20); //we allocate space for 20 elems
memset(this->rawData, 0, sizeof(T) * 20); //we zero it!
currentSize = 20;
dataPtr = static_cast<T*>(rawData); //we cast pointer to required datatype.
}
这部分是可以的 - 通过循环迭代并解除引用dataPtr的方式非常好。全是零。
然而,重新分配行为(在我看来)至少有点奇怪。首先你需要看一下重新分配的代码:
template <class T>
void dynArr<T>::insert(const int index, const T& data)
{
if (index < currentSize - 1)
{
dataPtr[index] = data; //we can just insert things, array is zero-d
}
else
{
//TODO we should increase size exponentially, not just to the element we want
const size_t lastSize = currentSize; //store current size (before realloc). this is count not bytes.
rawData = realloc(rawData, index + 1); //rawData points now to new location in the memory
dataPtr = (T*)rawData;
memset(dataPtr + lastSize - 1, 0, sizeof(T) * index - lastSize - 1); //we zero from ptr+last size to index
dataPtr[index] = data;
currentSize = index + 1;
}
}
简单来说,我们会将数据重新分配到索引+1的位置,并将未清零的内存设为0。
关于测试,我首先在这个数组的第5个位置插入了数字5。预期的结果发生了——
0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
然而,插入其他东西,比如insert(30,30),会给我带来奇怪的行为:0, 0, 0, 0, 0, 5, 0, -50331648, 16645629, 0, 523809160, 57600, 50928864, 50922840, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30,
我到底是哪里理解错了?realloc不应该考虑之前设置的20个内存字节吗?这里到底发生了什么黑魔法。
(index+1)
乘以sizeof(T)
。 - FBergorawData = realloc(rawData, index + 1);
如果这个操作失败了,你将会失去所有的数据。 - Baum mit Augenmalloc
和realloc
返回的原始内存块不包含任何对象,在使用放置new分配内存之前,必须先创建对象并进行赋值操作。否则将导致未定义的行为。 - Baum mit AugendataPtr[index] = data;
是错误的语法,这不是C语言... - Swift - Friday Pie