0

好的,我正在努力解决指针问题,但是一旦我开始使用类似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 会更好,但我正在尝试了解指针的工作原理。

4

2 回答 2

1

有两种方法可以解决问题:

  • Polygon保留 s 的副本Point(这使用Point *
  • Polygon2保持指向Points 的指针(这使用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];
}
于 2013-04-05T18:26:10.497 回答
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;

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

于 2013-04-05T18:37:48.600 回答