0

I have this code, however I am unsure of how to access the struct pointers after passing the struct by reference into a function, the program crashes on this line, accessing the pointers doesnt work.

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

FIXED CODE, thanks to all who answered

    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
  • apologies, i didnt explain what was actually going wrong, the program fails where I try to put stuff into the pointers Commented May 15, 2012 at 9:25
  • I have edited the tags. There are no references in C. Commented May 15, 2012 at 9:26
  • @n.m. There are no references in the code either; it looks like valid C to me (apart from the missing return in main of course). Commented May 15, 2012 at 9:29
  • @Mike: and apart from cout <<? Commented May 15, 2012 at 9:32

1 Answer 1

3

No memory has been allocated for xvals and yvals, they are uninitialsed pointers. numverts is also unintialised. You need to malloc() space for xvals and yvals and initialise numverts:

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

and prevent going beyond the end of these arrays, as this code does:

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

should be:

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

Remember to free() xvals and yvals when no longer required.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.