I am doing an assignment which requires me to write a code that contains a nested structure. The problem is actually pretty simple. Just to obtain coordinates of the corners of a rectangle. I have been researching online but most examples are without the typedef structure. My problem is mainly being unsure of what is the correct syntax to access and store the data. I have the structure templates as follows:
typedef struct
{
double x;
double y;
} Point; // Create a Point datatype;
typedef struct // nested structure
{
Point topLeft; // topLeft is the variable name for "Point" structure with x&y property
Point botRight; // botRight is the variable name for "Point" structure with x&y property
} Rectangle; // Create a Rectangle datatype with Point structure within
void getRect(Rectangle *r); // function prototype
int main()
{
Rectangle r; // initializing rectangle;
getRect(&r); // call function to get inputs using call by reference
}
void getRect(Rectangle *r)
{
printf("Enter top left points:\n");
scanf("%lf %lf", r->topLeft.x,r->topLeft.y); // Not sure if this is correct as my program can compile and run up till this point and crashes.
printf("Enter bottom right points:\n");
scanf("%lf %lf", r->botRight.x,r->botRight.y);
}
Seeking everyone's kind guidance on this matter!
The problem is that the arguments of the calls of scanf shall be pointers. For example
scanf("%lf %lf", &r->topLeft.x, &r->topLeft.y);
and
scanf("%lf %lf", &r->botRight.x, &r->botRight.y);
That is you need to pass objects x and y by reference that the function scanf could deal with the original objects instead of copies of their values.
In C passing by reference means passing objects indirectly through pointers to them. In this case the called function can get a direct access to the objects by using the dereferencing operation of the pointers.