此函数的目的是采用一个结构,并将数组扩大 1。它通过将数组复制到临时数组、删除并重新创建更大尺寸的原始数组来实现此目的。我的问题是,当我运行函数时,结构中的所有值都变成了“-17891602”。 如果我错了,请纠正我,但我相信这是在删除变量时显示的值?我无法弄清楚问题所在。但这是定义。
void Array::addValueStruct(int id, int size, int type, int compareValue, StoredData temp[])
{
//struct
StoredData* tempStruct = new StoredData [arrSize+1];
for (int i=0;i<arrSize;i++)
{
tempStruct[i] = temp[i];
}
arrSize = arrSize + 1;
delete [] temp;
temp = tempStruct;
temp[arrSize-1].id = id;
temp[arrSize-1].size = size;
temp[arrSize-1].type = type;
temp[arrSize-1].compareValue = compareValue;
}
此外,不确定这是否有帮助,但是函数调用。
test.addValueStruct(5,5,5,5,testData);
更新:问题已解决!
最佳答案
问题是数组指针是按值传递给函数的。这意味着当您将其重新分配为指向不同的数组时,此更改不会传播回调用方。
您需要通过指针或引用传递它。
关于c++ - 我的 C++ 函数在不应该的时候破坏了变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21075341/