I am new to C++ and working for an assignment, using C++98. I am trying to loop through an array of objects using pointer to array.
It is printing first point correctly, and after that some value.
Here are the code snippets:
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; } } this prints:
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 while the actual Points printed were:
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. referred this questions and this, but no success so far.