通过引用数组值进行交换
Swapping by reference array values
因此,在我执行此交换函数之后,数组中的所有值都将变为-858993460。为什么是这个数字?我想这是我声明数组的方式,但A这样声明不是指针吗?我想弄清楚为什么会这样。这是代码:
int* arrayCreate()//added mg
{
int a[] = { 3, 7, 4, 9, 5, 2 };
return a;
}
void Sort::Insert()
{
int t = 0;
//start clock
clock_t start = clock();
d = arrayCreate();
size = 6;
for (int i = 1; i< size; i++)
{
t = i;
while (((t - 1) >= 0) && (d[t] < d[t- 1]))
{
//Swap
Swap(d[t], d[t- 1]); // right after this call
//the debugger says values go to - 8e^8
t--;
}
}
}
void Sort::Swap(int& n1, int& n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}
您忽略了所有基于堆栈的变量在退出其定义的范围后都会被销毁。
因此,一旦返回A,它就会指向未定义的内存。
int* arrayCreate()//added mg
{
int a[] = { 3, 7, 4, 9, 5, 2 };
return a;
}
可以更改为此
int* arrayCreate()//added mg
{
static int a[] = { 3, 7, 4, 9, 5, 2 };
return a;
}
将数组标记为静态会导致内存滞留。
相关文章:
- 通过交换元素使数组相同
- 如何在数组中交换最小和最大的位置?
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 如何交换数组中的元素?
- C++:交换矩阵的行:使用单维数组
- 使用指针交换数组的内容
- 交换数组
- 代码是否交换数组的两个数字
- C++ 通过移动而不是复制来交换数组元素
- 为什么它不交换数组中的两个整数?
- 当数组是类的数据成员时,如何使用指针交换数组
- 无法在C++中交换数组中的对象
- 交换数组中的 2 个项目,但不通过引用传递它
- 我不知道如何打印数组,反过来,我也无法弄清楚如何交换数组中的元素
- 交换数组中的位置
- 不能交换数组元素 C++
- 如何在c++中基于输入整数值交换数组
- 在c++中可视化交换数组值
- 递归地交换数组中的元素
- 交换数组C++中的值