通过引用函数传递struct后访问struct指针

时间:2012-05-15 09:18:08

标签: c pointers struct pass-by-reference

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

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

1 个答案:

答案 0 :(得分:3)

没有为xvalsyvals分配内存,它们是未初始化的指针。 numverts也是未初始化的。 malloc()xvals需要yvals空格并初始化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