c ++如何使用动态指针数组?

时间:2013-04-05 18:14:48

标签: c++ pointers dynamic-arrays

好的,我正试图了解指针,但是一旦我开始使用类似class **c的东西,我就迷路了。

说我有

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];

此时,square应该包含一个指针数组,每个指针引用points中的一个点。然后

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

应将points[1].x更改为200。

如何将上述代码更改为实际执行此操作?虽然我明白使用std :: vector会更好,但我正在尝试学习指针是如何工作的。

2 个答案:

答案 0 :(得分:1)

有两种方法可以解决方案:

  • Polygon保留Point的副本(使用Point *
  • Polygon2保留指向Point的指针(使用Point **

以下是一个对OP代码进行一些修改的程序,它代表了两种方式。该代码也可在http://codepad.org/4GxKKMeh

获取
struct Point { int x, y, z; };

struct Polygon {
    // constructor: initialization and memory allocation
    Polygon( int sz ) : size( sz ), vertices( 0 ) {
        vertices = new Point[ size ];
    }
    ~Polygon() {
        delete [] vertices;
        vertices = 0;
    }
    int const size;
    Point * vertices; // note: single pointer; dynamically allocated array
};

struct Polygon2 {
    // constructor: initialization and memory allocation
    Polygon2( int sz ) : size( sz ), pPoints( 0 ) {
        pPoints = new Point * [ size ];
    }
    ~Polygon2() {
        delete [] pPoints;
        pPoints = 0;
    }
    int const size;
    Point ** pPoints; // note: double pointer; points to Points :-)
};


int main() {

    Point points[10];

    // Fill up the points
    // InputPoints(points, 10);

    Polygon square( 4 );
    square.vertices[0] = points[2];
    square.vertices[1] = points[4];
    square.vertices[2] = points[1];
    square.vertices[3] = points[7];

    Polygon2 square2( 4 );
    square2.pPoints[0] = & points[2];
    square2.pPoints[1] = & points[4];
    square2.pPoints[2] = & points[1];
    square2.pPoints[3] = & points[7];
}

答案 1 :(得分:1)

您可以执行以下操作:(假设vertices存储两个点)

 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;

您当然可以根据自己的需要更新。