在下面的函数中,我通过语句清楚地更改变量rightArray
:rightArray[i] = dataValues[i];
然而,我从函数得到的行为是变量leftArray
正在改变而不是rightArray
//Returns the interquartile range
float StatisticalAnalyser::getInterquartileRange()
{
float interquartileRange = 0;
int numberOfDatums = dataFile.findNumberOfDatums();
float numberOfDatumsFloat = dataFile.findNumberOfDatums();
float dataValues[dataFile.findNumberOfDatums()];
dataFile.initialiseArrayToFileData(dataValues);
//If even number of datums
if (numberOfDatums % 2 == 0)
{
//Arrays for for each side of the median
int arraySize = numberOfDatumsFloat/2;
float leftArray[numberOfDatums/2];
float rightArray[numberOfDatums/2];
//Initialise arrays for each side of the median
for (int i = 0; i < numberOfDatums; i++)
{
if (i < numberOfDatums/2)
{
leftArray[i] = dataValues[i];
}
if (i >= numberOfDatums/2)
{
//leftArray SOMEHOW GETS CHANGED INSTEAD OF RIGHT ARRAY
rightArray[i] = dataValues[i];
leftArray在这里改变而不是rightArray:rightArray[i] = dataValues[i];
}
}
}
if (numberOfDatums % 2 == 0.5)
{
//Not relevant, isn't triggered when problem occurs
}
return interquartileRange;
}
我正在运行Xcode 10.1,并想知道如何修复此错误,以便rightArray
由函数而不是leftArray
更改。
有
float leftArray[numberOfDatums/2];
float rightArray[numberOfDatums/2];
在
if (i >= numberOfDatums/2)
{
//leftArray SOMEHOW GETS CHANGED INSTEAD OF RIGHT ARRAY
rightArray[i] = dataValues[i];
你走出rightArray并随机写入leftArray(当然这是一个未定义的行为)
一定是
if (i >= numberOfDatums/2)
{
rightArray[i - numberOfDatums/2] = dataValues[i];
而且,有
if (i < numberOfDatums/2)
{
...
}
if (i >= numberOfDatums/2)
如果我没有改变是无用的,第二个如果可以是其他的,但最好做两个,因为不必一直做numberOfDatums/2
只是为了决定使用哪个数组。