c++ - 在数组内移动项目的函数中的奇怪行为
问题描述
我有一个像这样调用的函数
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
首先需要它。为什么它不能只使用我最初传递给它的数组。为什么当我不要求它改变时它会改变?
我试过了
- 将尺寸添加到
arrz
- 制作
arrz
static
而不是const
- 不做(
returnarray
这static
更打破了它) - 使用
returnarray
初始值= { 0,0,0,0,0,0,0 }
uselessarray
除了宣布作品之外别无他法。这里发生了什么?
解决方案
适用于您的示例的函数可能如下所示:
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;
}
[这里的工作示例]
请注意,此代码在原始数组中就地进行更改。如果您需要创建一个新数组并返回,那么我建议您将新数组作为指向其第一个元素的指针传递。
虽然这适用于问题中显示的示例,但它可能不适用于我们未知的其他情况。
推荐阅读
- javascript - 将 jQuery 动画转换为 React Hook
- php - 将变量值设置为 json 参数 - PHP
- python - Spyder 中没有名为“pyodbc”的模块
- discord.js - 如何发出拍卖指令
- android - 无法在 android 开发中使用 ML Kit
- elasticsearch - 在您的集群中找不到 magento 2.4.1 的活动节点
- jquery - Portfolio Builder 不再与 WordPress 5.7 兼容
- javascript - 收集属性值并将其显示在 DOM whit JavaScript
- module - 错误:12014 - 我无法将优先电路模块与七段模块链接
- javascript - Crud,put 函数的错误