65,189
社区成员




// 函数随机生成5个点,然后传出
#include <iostream>
#include <ctime>
using namespace std;
const int len = 5;
typedef struct
{
int x;
int y;
void show()
{
cout << "(" << x << " , " << y << ")" << endl;
}
}point;
point* GetRandomPoint(int) // 这个函数因为返回了临时数组ptArr,函数结束时,ptArr内存被回收,导致结果不正确
{
srand((unsigned)time(NULL));
point ptArr[len];
int x, y;
for (int i = 0; i < len; ++i)
{
x = rand() % 50;
y = rand() % 50;
ptArr[i].x = x;
ptArr[i].y = y;
}
return ptArr;
}
point* GetRandomPoint() // 这个函数返回了动态分配的数组,程序主程序退出前或者手动delete前,这段内存一直存在
{
srand((unsigned)time(NULL));
point* ptArr = new point[len];
int x, y;
for (int i = 0; i < len; ++i)
{
x = rand() % 50;
y = rand() % 50;
ptArr[i].x = x;
ptArr[i].y = y;
}
return ptArr;
}
int main()
{
point* pt = GetRandomPoint(); // 这里括号随便填个整形参数,就能调用错误的函数
for (int i = 0; i < len; ++i)
pt[i].show();
delete[] pt; // 这里别忘了delete
return 0;
}