错误:在“.”之前应有“=”、“,”、“;”、“asm”或“__attribute__” C 程序中的令牌

-1 c compiler-errors data-structures

#include <stdio.h>

struct point {
    int x;
    int y;
};

struct rectangle {
    struct point upper_left;
    struct point lower_right;
};

double calcul_area(struct rectangle a) {
    double width = a.lower_right.x - a.upper_left.x;
    double height = a.upper_left.y - a.lower_right.y;
    return width * height;
}

struct rectangle r;
r.upper_left.x = 3;
r.upper_left.y = 9;
r.lower_right.x = 12;
r.lower_right.y = 2;


int main() {
    printf("the size of rectangle is %f", calcul_area(r)); 
}
Run Code Online (Sandbox Code Playgroud)

这段代码用于计算轴 $x$,$y$ 的矩形面积。我不想谈论代码的想法,但我只是想了解为什么会显示此错误。请注意代码当我在主函数下编写上述部分代码时工作正常,但是当我将其放在主函数之前时我看到错误

struct rectangle r;
r.upper_left.x = 3;
r.upper_left.y = 9;
r.lower_right.x = 12;
r.lower_right.y = 2;
Run Code Online (Sandbox Code Playgroud)

Mik*_*CAT 5

您无法编写在全局范围内以这种方式执行的代码。

struct rectangle r;
r.upper_left.x=3;
r.upper_left.y=9;
r.lower_right.x=12;
r.lower_right.y=2;
Run Code Online (Sandbox Code Playgroud)

您可以这样编写初始值(C99 或更高版本):

struct rectangle r = {
    .upper_left = { .x = 3, .y = 9 },
    .lower_right = { .x = 12, .y = 2 }
};
Run Code Online (Sandbox Code Playgroud)