c - 在函数中返回结构,编译错误

标签 c function struct

我正在练习我的 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;
}

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

*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;
^

如果我遗漏了一些信息,请告诉我

谢谢你:)

最佳答案

您的函数的返回类型是struct rect。 NULL 是指针或 0。您应该返回 struct rect 或将函数的返回类型更改为 struct rect* 和指向堆的指针 malloc 改为 struct rect

关于c - 在函数中返回结构,编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20389227/

相关文章:

c - C 语言中的 OpenMP + MPI 混合 - 编译困难

function - OCaml:迭代列表并跳过错误构造函数的元素

C - 自定义 qsort 不工作

c# - 为什么我们不能使用动态方法来代替 Generic(T) 方法

c++ - 结构未完成排序

c++ - 打印一个结构指针和一个引用的结构成员

c - 返回计算翻译的程序的结构

c - C中的转义字符

c - 在 C 中包含库失败

c - 段错误 - 无效的自由未解决 - C