-5

I have a class point.

I have an event call onPoint change. This may occur any number of times. In each event a new point is given by the event. So I don't know in advance how may points to be allocated in advance. It may but 1 2 or hundreds.

So I thought of using dynamic memory allocation. So I created a pointer p of type Point.

I allocated a reference memory by point* p = (point*)malloc(sizeof(p));

Inside the main method the first point is inserted (0, 0). All other points are inserted in the onPointChange Event.

Now I want, the point that are detected in onPointChange event to be appended in my pointer (p) also all of its previous values are preserved. And finally print them.

#include <iostream>
#include <string>
#include <array>

using namespace std;

class point {
    public:
    int x;
    int y;
};

point* p = (point*)malloc(sizeof(p));
int main()
{
   p.x =0;
   p.y =0;

  // Now all other points to be filled in onPointChange event
}

void onPointChange(){
 point newpoint;
 newpoint.x = newXValue;
 newpoint.y = newYValue;
 // Here I need to reallocate my pointer p such that the new point (newpoint) is appended to the p and also all of its earlier elements are preserved.
// And after meeting any condition, print the value of x and y of all points in p
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

2

You cannot "append" to a pointer. You can use a std::vector to store the points as needed, and then print the points in the vector when your condition is met.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
user18359
  • 76
  • 2