Home > OS >  Why does my structures fail to create a rectangle in C?
Why does my structures fail to create a rectangle in C?

Time:12-31

I was given this simple task:

  1. A "rectangle" structure must be defined by 2 points - the edges of the diagonal. The following functions must be set: A. Rectangle input. B. A function that receives a rectangle and returns its area. C. A function that receives a rectangle and a dot. The function returns TRUE in case the point is found Inside the rectangle, otherwise it returns FALSE.

and here is my code:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

// ex1
typedef struct{
    double x;
    double y;
} Point;

typedef struct{
    Point a;
    Point b;
} Rect;

void ex1_1(Rect rect1);
double ex1_2(Rect rect1);
int ex1_3(Rect rect1, Point a);

int main()
{
    Rect r;
    Point p1 = {2, 2}, p2 = {10, 10};
    ex1_1(r);
    printf("%lf\n", ex1_2(r));
    printf("%d\n", ex1_3(r, p1));
    printf("%d\n", ex1_3(r, p2));
    return 0;
}

void ex1_1(Rect rect1)
{
    Point p1, p2;
    printf("Enter the bottom left edge (x y): ");
    scanf_s("%lf%lf", &p1.x, &p1.y);
    printf("Enter the top right edge (x y): ");
    scanf_s("%lf%lf", &p2.x, &p2.y);
    rect1.a = p1; rect1.b = p2;
}

double ex1_2(Rect rect1)
{
    return (rect1.b.x - rect1.a.x) *
           (rect1.b.y - rect1.a.y);

}

int ex1_3(Rect rect1, Point p)
{
    return rect1.a.x < p.x && p.x < rect1.b.x &&
           rect1.a.y < p.y && p.y < rect1.b.y;
}

However, when I run my program is prints me only zeroes, why is that?

CodePudding user response:

You are passing an uninitialized variable to the ex_1_1 function, this is undefined behaviour. Also, passing a copy of the variable to the function doesn't alter the contents of r inside main.

Pass a pointer:

void ex1_1(Rect *rect1);

int main()
{
    Rect r;
    Point p1 = {2, 2}, p2 = {10, 10};
    ex1_1(&r);
    ...
}

void ex1_1(Rect *rect1)
{
    Point p1, p2;
    printf("Enter the bottom left edge (x y): ");
    scanf("%lf%lf", &p1.x, &p1.y);
    printf("Enter the top right edge (x y): ");
    scanf("%lf%lf", &p2.x, &p2.y);
    rect1->a = p1; rect1->b = p2;
}
  • Related