首页 > 解决方案 > 在数组内移动项目的函数中的奇怪行为

问题描述

我有一个像这样调用的函数

arraypointer = move(arraypointer, item, remove_location, move_location)

(它在另一个arraypointer经常使用的函数中调用自己。)

所以如果我有一个这样的数组

1 2 3 0 4 5 6

我打电话给

arraypointer = move(arraypointer, 0, 3, 0)

它会回来

0 1 2 3 4 5 6

这是代码

int* move(const int arrz[], const int mvalue, const int rlocation, const int mlocation) {
    static int uselessarray[7] = { 0 };
    uselessarray[0] = arrz[0];
    uselessarray[1] = arrz[1];
    uselessarray[2] = arrz[2];
    uselessarray[3] = arrz[3];
    uselessarray[4] = arrz[4];
    uselessarray[5] = arrz[5];
    uselessarray[6] = arrz[6];

    static int returnarray[7];
    returnarray[0] = 1;
    int i = 0; int j = 0;

    
    
    for (i = 0; i < 7; i++) {
        if (i == mlocation) {
            j++;
            returnarray[mlocation] = mvalue;
        }
        if (i == rlocation) {
        }
        else {
            returnarray[j] = uselessarray[i];
            //returnarray[j] = arrz[i];
            j++;
        }
        
    }
    return returnarray;
}

如果我不初始化uselessarray并从中复制数据arrz。然后当我改变returnarray它时也 changez arrz。即使arrz是一个常数,我也绝不要求改变它。它完全符合我在上面粘贴的代码的要求。但我试图弄清楚为什么我uselessarray首先需要它。为什么它不能只使用我最初传递给它的数组。为什么当我不要求它改变时它会改变?

我试过了

  1. 将尺寸添加到arrz
  2. 制作arrz static而不是const
  3. 不做(returnarraystatic更打破了它)
  4. 使用returnarray初始值= { 0,0,0,0,0,0,0 }

uselessarray除了宣布作品之外别无他法。这里发生了什么?

标签: c++arrayscfunctionpointers

解决方案


适用于您的示例的函数可能如下所示:

void move(int arrz[], const int mvalue, const int rlocation, const int mlocation)
{
    // Get a copy of the value to "move"
    int value = arrz[mlocation];

    // Move (part) of the array one step to the right
    memmove(&arrz[rlocation + 1], &arrz[rlocation], (mlocation - rlocation) * sizeof(int));

    // And copy the value to its destination place
    arrz[rlocation] = value;
}

[这里的工作示例]

请注意,此代码在原始数组中就地进行更改。如果您需要创建一个新数组并返回,那么我建议您将新数组作为指向其第一个元素的指针传递。

虽然这适用于问题中显示的示例,但它可能不适用于我们未知的其他情况。


推荐阅读