正在构建一个处理结构的简单程序。逻辑很简单,但由于某种原因,我无法完全弄清楚如何将结构传递给函数。我在 main() 中声明了该结构。通过搜索网站,我得到的印象是,执行此操作的唯一方法是创建头文件并以这种方式声明。这是真的吗?
main() {
struct Rect {
double x;
double y;
char color;
double width;
double height;
};
struct Rect a, b, *rec;
这就是我试图传递它的地方:
int chk_overlap(struct Rect *r1, struct Rect *r2) {
if(((r1->x + r1->width) >= r2->x) && ((r1->y) >= (r1->y - r2->height))){
return 1;
} else {
return 0;
}
}
这只是我尝试的一次迭代,当我像这样传递它时,我收到了对不完整指针错误的取消引用。我也尝试过将其声明为
typedef struct Rect {
double x;
double y;
char color;
double width;
double height;
} Rect;
Rect a, b, *rec;
将其传递为
int chk_overlap(Rect *r1, Rect *r2) {
编辑:这是我实际使用该功能的地方
int check = 0;
check = check + chk_overlap(&a, &b);
最佳答案
您应该在 main 之前声明结构。
struct Rect {
double x;
double y;
char color;
double width;
double height;
}
/* Place here the function definitions */
int main (int argc, char *argv[]) {
struct Rect a, b, *rec;
...
}
/* place here the function code */
由于您在 main() 内部声明它,因此在外部看不到它,因此函数无法识别它。
除此之外,您调用函数的方式 (function(&a, &b)
) 看起来是正确的。
关于c - 需要帮助在 C 中将结构传递给本地函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346619/