gpt4 book ai didi

c++ - 为什么指针数组会在函数完成时自行初始化?

转载 作者:行者123 更新时间:2023-11-28 00:50:51 26 4
gpt4 key购买 nike

我的周末作业是创建一个函数,该函数获取一个整数数组和数组的大小,并创建一个指针数组,以便使用冒泡排序对指针进行排序(无需更改原始数组)。

调试时我发现它工作得很好,但是当函数返回到 main() 时,指针数组被初始化,一切都消失了。

#include <iostream>
using namespace std;

void pointerSort(int arr[], int size, int* pointers[]);
void swap(int a, int b);
void main()
{
int arr[5]={7,2,5,9,4};
int size = 5;
int* pointers[5];

pointerSort(arr, size, pointers);

for (int i = 0; i < 5 ; i++)
cout << *pointers[i] << endl;
}
void pointerSort(int arr[], int size, int* pointers[])
{
int j, i;
bool change = true;

pointers = new int*[size];
for (i = 0; i < size; i++)
pointers[i] = &arr[i];

i = 0;
j = 1;
while (i <= size-1 && change == true)
{
change = false;
for (i = 0; i < size-j; i++)
{
if (*pointers[i] > *pointers[i+1])
{
swap(pointers[i], pointers[i+1]);
change = true;
}
}
j++;
}
}
void swap(int&a, int&b)
{
int temp;

temp = a;
a = b;
b = temp;
}

最佳答案

pointers = new int*[size];

此时pointers已经是一个指针数组,不需要分配。

在这一行之后 pointers 不再是你的 MAIN 函数中的数组

这就是您的函数失败的原因,因为您正在重新分配 pointers 指向的数组。原始数组 ISNT 被重新初始化,它只是在整个代码中被忽略。

它也是一个memory leak正如 ATaylor 提到的那样,因为您没有删除分配的空间,并且在函数完成后无法删除空间。

要修复所有问题:只需删除上面的行。

关于c++ - 为什么指针数组会在函数完成时自行初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14170686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com