错误的数组变量被更改

时间:2019-02-23 15:54:49

标签: c++ arrays xcode for-loop output

在以下函数中,我通过以下语句清楚地更改了变量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

1 个答案:

答案 0 :(得分: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)
保留 i 不变的

是没有用的,第二个 if 可以是 else ,但是最好同时做两个 不必总是做numberOfDatums/2来决定要使用哪个数组。