使用指向数组的指针遍历对象数组

Iterating through array of object using pointer to array

我是 C++ 的新手,正在为一项使用 C++98 的作业工作。我正在尝试使用指向数组的指针遍历对象数组。

它正在正确打印第一个点,然后是一些值。

以下是代码片段:

struct Point { int x, y; };
int randomNumber(int low, int high ) {
   int randomNumber = low + (rand())/ (RAND_MAX/(high-low));
   cout << setprecision(2);
   return randomNumber;
}

Point *generateCoordinates(int nodesPerBlock) {
    Point cities[nodesPerBlock];
    for (int i = 0; i < nodesPerBlock; i++) {
        cities[i].x = randomNumber(1, 50);
        cities[i].y = randomNumber(1, 50);
    }
    return cities;
}
int main() {
  int nodesPerBlock = 5;
  Point *points = generateCoordinates(nodesPerBlock);
  for (int n = 0; n < (nodesPerBlock-2); n++) {
    cout << "n: x=" << points[n].x << ", y=" << points[n].y << endl;
    cout << "n+1: x=" << points[n+1].x << ", y=" << points[n+1].y << endl;
  }
}

这会打印:

n: x=1, y=4
n+1: x=18, y=11
n: x=2049417976, y=32767
n+1: x=2049417976, y=32767
n: x=2049417976, y=32767
n+1: x=2049417984, y=167804927

而实际打印的点数是:

Point : x=1, y=4.
Point : x=18, y=11.
Point : x=13, y=6.
Point : x=2, y=16.
Point : x=16, y=22.

推荐 and ,但目前还没有成功。

cities[nodesPerBlock]generateCoordinates 函数中的局部变量,当函数退出时它超出范围。
您正在 return 获取它的地址并在 main 中访问该地址。这是未定义的行为。

您必须使用 new(因为您使用的是 C++98)在堆上分配 cities,然后 return 该地址到 main。然后您将能够可靠地访问该地址。

处理完成后,不要忘记删除在main末尾分配的内存。

您可以通过更改您的函数以采用可以从 main 传递的额外参数来避免内存分配和删除。那么cities可以是栈上Point的数组

void generateCoordinates(Point cities[], int nodesPerBlock);