c++函数内再赋值并返回问题
本帖最后由 FISHER666 于 2020-4-12 12:09 编辑提问,为什么整型数组再次赋值并返回,还是原来那个数组? 问题来源于33到40行代码
# include <iostream>
# include <cstdlib>
# include <ctime>
using namespace std;
// 为了return数组,必须定义指针函数
int *range(int arr);
//冒泡排序找最大值,为了保证普适性,其数组长度应该为输入的数组长度相同
int *range(int arr[], int num)
{
int arr1;
for (int k = 0;k < num;k++)
{
arr1 = arr;
}
for(int i = 0; i < num - 1; i++)
{
for (int j = 0;j < num - i - 1; j++)
{
if (arr1 > arr1) //这里要打括号
{
int temp = arr1;
arr1 = arr1;
arr1 = temp;
}
}
}
// 反向复制一次,并返回
for (int k = 0;k < num;k++)
{
arr = arr1;
}
return arr;
}
int main()
{
int arr1;
// 随机生成一维数组
srand((int)time(NULL));// 产生随机种子
for (int i = 0; i < 10; i++)
{
arr1 = rand()%100;
}
for (int i = 0; i < 10; i++)
{
cout<<arr1<<" ";
}
cout<<endl;
// 获得排序后的数组
int *arrA;
arrA = range(arr1,10);
for (int i = 0; i < 10; i++)
{
cout<<arrA<<" ";
}
cout<<endl;
system("pause");
return 0;
} # include <iostream>
# include <cstdlib>
# include <ctime>
using namespace std;
// 为了return数组,必须定义指针函数
int* range(int *arr,int num);
//冒泡排序找最大值,为了保证普适性,其数组长度应该为输入的数组长度相同
int* range(int *arr,int num)
{
int* arr1 = new int;//数组动态分配
for (int k = 0; k < num; k++)
{
arr1 = arr;
}
for (int i = 0; i < num - 1; i++)
{
for (int j = 0; j < num - i - 1; j++)
{
if (arr1 > arr1) //这里要打括号
{
int temp = arr1;
arr1 = arr1;
arr1 = temp;
}
}
}
// 反向复制一次,并返回
for (int k = 0; k < num; k++)
{
arr = arr1;//反向复制需要-1,因为num下标最大为 num-1,arr下标应该是k,不是num
}
return arr;
}
int main()
{
int arr1;
// 随机生成一维数组
srand((int)time(NULL));// 产生随机种子
for (int i = 0; i < 10; i++)
{
arr1 = rand() % 100;
}
for (int i = 0; i < 10; i++)
{
cout << arr1 << " ";
}
cout << endl;
// 获得排序后的数组
int* arrA;
arrA = range(arr1, 10);
for (int i = 0; i < 10; i++)
{
cout << arrA << " ";
}
cout << endl;
system("pause");
return 0;
} 奇宝 发表于 2020-4-12 16:15
# include
# include
# include
感谢指导!
页:
[1]