错误的数组变量发生了变化

问题描述 投票:-2回答:1

在下面的函数中,我通过语句清楚地更改变量rightArrayrightArray[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更改。

c++ arrays xcode for-loop output
1个回答
1
投票

    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只是为了决定使用哪个数组。

© www.soinside.com 2019 - 2024. All rights reserved.