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

标签 c++ arrays pointers c++98

我是 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.

引用this questionsthis , 但到目前为止没有成功。

最佳答案

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

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

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

您可以通过更改您的函数以获取一个您可以从 main 传递的额外参数来避免内存分配和删除。然后 cities 可以是堆栈上的 Point 数组。

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

关于c++ - 使用指向数组的指针遍历对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53312832/

相关文章:

c++ - 每个的附加条件

javascript - 获取多个数组中给定索引处所有元素的平均值

python - 将值分配给 numpy 数组中的位置而不修改数组

c++ - 如何从枚举类型中获取枚举值?

c++ - 转发声明枚举类不起作用

c++ - 带有 boost 测试的 Autoconf - 链接器问题

javascript - PHP array() 到 javascript array()

malloc() 可以用来定义数组的大小吗?

c++ - 指向动态数组的指针数组 : how to access without variable name

c - 为结构化指针分配内存