在Function,Compile错误中返回struct

Gök*_*Nas 1 c struct function

我正在练习我的C编程语言技能,当我写这个代码编译器显示一堆错误但我没有看到这有什么问题.我在互联网上学到了这个代码所以希望你能帮助我:)

这是代码;

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;
}
Run Code Online (Sandbox Code Playgroud)

编译错误在rect intersection = {.x1 = m.x1,.y1 = m.y2,.x2 = n.x2,.y2 = n.y2};*错误:字段名称不在记录或联合初始值设定项中

*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;
^
Run Code Online (Sandbox Code Playgroud)

如果我错过了一些信息,请告诉我

谢谢 :)

Jul*_*.M. 5

你的函数的返回类型是struct rect.NULL是一个指针或0.您应该返回struct rect或更改函数的返回类型struct rect*和一个指向堆malloc"D struct rect来代替.

  • 这是两个问题之一; 另一个是缺少关键字`struct`.在C++中,您不需要重复`struct`,但这是C. (2认同)