Reputation: 213
I am practicing on my C programming language skills and when i wrote this code compiler shows a bunch of error but i did not saw what is wrong with this. I am learnt this code on internet so hopefully you can help me :)
here is the code;
struct rect {
int x1;
int y1;
int x2;
int y2;
};
struct rect intersection(struct rect m, struct rect n) {
struct rect intersection;
if((n.x1 > m.x1) && (n.x1 < m.x2) && (n.y1 > m.y1 ) && (n.y1 < m.y2)){
rect intersection = {.x1=n.x1, .y1=n.y2, .x2=m.x2, .y2=m.y2};
return intersection;
}
else if((m.x1 > n.x1) && (m.x1 < n.x2) && (m.y1 > n.y1 ) && (m.y1 < n.y2)){
rect intersection = {.x1=m.x1, .y1=m.y2, .x2=n.x2, .y2=n.y2};
return intersection;
}
return NULL;
}
compile errors are at rect intersection = {.x1=m.x1, .y1=m.y2, .x2=n.x2, .y2=n.y2}; *error: field name not in record or union initializer
*error: incompatible types when returning type ‘int’ but ‘struct rect’ was expected
return intersection;
^
*error: incompatible types when returning type ‘void *’ but ‘struct rect’ was expected
return NULL;
^
IF I MISS SOME INFO , PLEASE TELL ME
THANK YOU :)
Upvotes: 1
Views: 4860
Reputation: 3781
The return type of your function is struct rect
. NULL is a pointer or 0. You should either return a struct rect
or change the return type of your function to struct rect*
and a pointer to a heap malloc
'd struct rect
instead.
Upvotes: 5
Reputation: 58868
user2151287 suggested returning a pointer; but then you need something to point to, because
// this code is wrong
struct rect *some_function()
{
struct rect x = {stuff};
return &x;
}
is undefined behaviour - it has a chance of working anyway depending on how you use it, but eventually it won't work, and you'll be very confused.
You could return an empty rectangle (width and height = 0) instead:
struct rect x = {.x1=0, .y1=0, .x2=0, .y2=0};
return x;
By the way, your intersection
function returns the wrong result in this case:
Upvotes: 1
Reputation: 763
struct rect intersection = {.x1=n.x1, .y1=n.y2, .x2=m.x2, .y2=m.y2};//like this
return NULL;//return intersection
My proposal is using pointer:the function return struct rect *
,if this,you can return NULL
when there is some error.
Upvotes: 2