Search code examples
c++pointersdynamic-arrays

c++ How do I use a dynamic array of pointers?


Ok, I'm trying to get my head around pointers but once I start using something like class **c i get lost.

Say I had

struct POINT{ int x, y, z; };
struct POLYGON{ POINT **vertices; int size; };

POINT points[10];
InputPoints(points,10); //fills up the points array somehow

POLYGON square;
//the following is where I'm lost
square.vertices = new *POINT[4];
square.vertices[0] = *points[2];
square.vertices[1] = *points[4];
square.vertices[2] = *points[1];
square.vertices[3] = *points[7];

At this point, square should hold an array of pointers that each reference a point in points. Then

square.vertices[2].x = 200; //I think this is done wrong too

should change points[1].x to 200.

How would I change the above code to actually do this? And while I understand that using std::vector would be better, I'm trying to learn how pointers work.


Solution

  • You can do something like the following: (assuming that vertices stores two point)

     POINT points[2];
     POINT  p1 = {10,20,30};
     POINT  p2 =  {20,30,50};
     points[0] = p1 ;
     points[1] = p2;
    
    POLYGON square;
    //the following is where I'm lost
    square.vertices  = new POINT*[2]; //pay attention to syntax
    square.vertices[0] = &points[0];  //vertices[0] stores first point
    square.vertices[1] = &points[1];  //you should take address of points
    
    square.vertices[0][0].x = 100;
    std::cout << square.vertices[0][0].x 
        <<std::endl;  //this will change the first point.x to 100
    return 0;
    

    You can certainly update this according to your needs.