Question

am building a simple program dealing with structs. The logic is simple enough but for some reason I can't quite figure out how to pass the struct to a function. I declared the struct in my main(). I got the impression from searching the site that the only way to do this is to create a header file and declare that way. Is this true?

 main() {

    struct Rect {
            double x;
            double y;
            char color;
            double width;
            double height;

    };



    struct Rect a, b, *rec;

and this is where I am trying to pass it:

int chk_overlap(struct Rect *r1, struct Rect *r2) {
    if(((r1->x  + r1->width) >= r2->x) && ((r1->y) >= (r1->y - r2->height))){
            return 1;
    } else {
            return 0;
    }
}

This is just one iteration of my attempt, when I pass it like this, I get a dereferencing to incomplete pointer error. I have also tried declaring it as

typedef struct Rect {
            double x;
            double y;
            char color;
            double width;
            double height;

    } Rect;

Rect a, b, *rec;

passing it as

int chk_overlap(Rect *r1, Rect *r2) {

EDIT: This is where I am actually using the function

        int check = 0;
    check = check + chk_overlap(&a, &b);
Was it helpful?

Solution

You should declare the structure before the main.

struct Rect {
    double x;
    double y;
    char color;
    double width;
    double height;
}

/* Place here the function definitions */

int main (int argc, char *argv[]) {
    struct Rect a, b, *rec;
    ...
}

/* place here the function code */

Since you're declaring it inside the main() it's not seen outside, so functions don't recognise it.

Other than that, the way you're calling the function (function(&a, &b)) looks correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top