使用指针访问嵌套结构中的数据

我正在做一项作业,要求我编写一个包含嵌套结构的代码。问题其实很简单。只是为了获得矩形角的坐标。我一直在网上研究,但大多数例子都没有 typedef 结构。我的问题主要是不确定访问和存储数据的正确语法是什么。我的结构模板如下:

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);
}

求大家多多指教!

回答

问题是 scanf 调用的参数应该是指针。例如

scanf("%lf %lf", &r->topLeft.x, &r->topLeft.y);

scanf("%lf %lf", &r->botRight.x, &r->botRight.y);

也就是说,您需要通过引用传递对象 x 和 y,函数 scanf 可以处理原始对象而不是它们值的副本。

在 C 中,通过引用传递意味着通过指向对象的指针间接传递对象。在这种情况下,被调用函数可以通过使用指针的解引用操作直接访问对象。


以上是使用指针访问嵌套结构中的数据的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>