简体   繁体   English

Typedef 结构、指针和指向 function 的指针

[英]Typedef struct, pointers and passing pointers to a function

Im kinda new to programming, so if someone could help me here id appreciate it!我对编程有点陌生,所以如果有人可以在这里帮助我,我将不胜感激!


typedef struct /*struct for circle creation*/
{
  int x_coord;
  int y_coord;
  int radius;
} circle, *circlepointer;

I need a pointer to a circle, and pass that pointer to a function that returns true if the circle radius is >0, and false otherwise.我需要一个指向圆的指针,然后将该指针传递给 function,如果圆半径大于 0,则返回 true,否则返回 false。 How do i pass my *circlepointer to a function and check this?我如何将我的 *circlepointer 传递给 function 并检查这个? I should be able to do something like circle.radius > 0, in the function我应该能够在 function 中执行类似 circle.radius > 0 的操作

Hope you can help希望你能帮忙

The function can be declared like function 可以这样声明

int f( circlepointer c );

or或者

int f( const circle *c );

and called like并称为

circle c = { /*...*/ };

f( &c );

Within the function you can access data members of the object like c->radius or ( *c ).radius .在 function 中,您可以访问 object 的数据成员,例如c->radius( *c ).radius

Instead of the return type int you can also use the C type _Bool.除了返回类型 int,您还可以使用 C 类型 _Bool。 Or you can include the header <stdbool.h> and write the return type as bool .或者您可以包含 header <stdbool.h>并将返回类型写为bool

Pay attention to that these two function declarations注意这两个 function 声明

int f( const circlepointer c );

and

int f( const circle *c );

are not equivalent.不等价。 In the first declaration the pointer itself is constant.在第一个声明中,指针本身是常量。 In the second declaration the object pointed to by the pointer is constant.在第二个声明中,指针指向的 object 是常量。

You can declare and define your function in this way您可以通过这种方式声明和定义您的 function

int func(circle * c) {
    return c->radius > 0;
}

Access a member via pointer can be done with -> operator or by dereferencing the pointer and then just use.通过指针访问成员可以使用 -> 运算符或通过取消引用指针然后使用来完成。 operator to access its members操作员访问其成员

(*c).radius 
c->radius

then just call it in main然后在 main 中调用它

circle c = {your_x, your_y, your_radius};
func(&c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM