简体   繁体   中英

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. How do i pass my *circlepointer to a function and check this? I should be able to do something like circle.radius > 0, in the function

Hope you can help

The function can be declared like

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 .

Instead of the return type int you can also use the C type _Bool. Or you can include the header <stdbool.h> and write the return type as bool .

Pay attention to that these two function declarations

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.

You can declare and define your function in this way

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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