0

我有这段代码,但是我不确定在通过引用将结构传递给函数后如何访问结构指针,程序在这一行崩溃,访问指针不起作用。

    scanf("(%lf,%lf)",polygon->xvals[i],polygon->yvals[i]);

固定代码,感谢所有回答的人

    struct Polygon{
    double *xvals, *yvals;
    int numverts;
    };
    typedef struct Polygon pol;
    pol getpoly(pol *polygon);


    int main(){
     pol polygon;
     getpoly(&polygon);  
            }


    pol getpoly(pol *polygon){
      polygon->xvals = (double * )malloc(sizeof(double)*polygon->numverts);
      polygon->yvals = (double * )malloc(sizeof(double)*polygon->numverts); 

      check=0;
      int i;

      for(i=0;i<10;i++){

       while(check !=2 ){
        cout<<"enter vertices "<<i<<" (x,y)\n";
        check = scanf("(%lf,%lf)",&polygon->xvals[i],&polygon->yvals[i]);
        _flushall();
       }
      check=0; 
      }
      polygon->xvals[polygon->numverts-1] = polygon->xvals[0];
      polygon->yvals[polygon->numverts-1] = polygon->yvals[0]; 

    return *polygon;    
    }
4

1 回答 1

3

没有为xvals和分配内存yvals,它们是未初始化的指针。numverts也是未初始化的。您需要留出malloc()空间xvalsyvals初始化numverts

polygon->numverts = 10;
polygon->xvals = malloc(polygon->numverts * sizeof(double));
polygon->yvals = malloc(polygon->numverts * sizeof(double));

并防止超出这些数组的末尾,就像这段代码一样:

polygon->xvals[polygon->numverts] = polygon->xvals[0];
polygon->yvals[polygon->numverts] = polygon->yvals[0];

应该:

polygon->xvals[polygon->numverts - 1] = polygon->xvals[0];
polygon->yvals[polygon->numverts - 1] = polygon->yvals[0];

请记住free() xvalsyvals何时不再需要。

于 2012-05-15T09:25:05.887 回答