0

I'm writing a function which compares the id of two vertices.

/* Returns whether aim and vertex have the same id */

bool id_eq(void *aim, void *vertex) {
    if(*(Vertex)aim.id ==*(Vertex)vertex.id){
        return true;
}
    return false;
}

aim and vertex are two pointers of struct vertex_t.

typedef struct graph_t* Graph;
typedef struct vertex_t* Vertex;

/* A vertex is an id, a label and a list of incoming and outgoing edges */
struct vertex_t {
    int id;
    char *label;

    /* A list of vertices representing incoming edges */
    List in;
    /* A List of vertices representing outgoing edges */
    List out;
};

But when I compiled it, an error occurred as 'ERROR:request for member 'id' in something not a structure or union'. Could someone please tell me where I went wrong???

Abby Meng
  • 13
  • 4
  • `.` can only be used with a struct or union. `aim` is a pointer. You probably meant `((Vertex)aim)->id == ((Vertex)vertex)->id`. – M.M Mar 27 '16 at 02:10
  • Avoiding pointer typedefs would make your code easier to read – M.M Mar 27 '16 at 02:11
  • I tried to use (Vertex)aim -> id, but this error still occurred. – Abby Meng Mar 27 '16 at 02:14
  • If I use *(Vertex)aim.id, does it make (*aim) a struct with type vertex_t? – Abby Meng Mar 27 '16 at 02:16
  • `aim->id` is an error because `aim` has type `void *`, it does not have any member called `id`. Use what I suggested in my first comment. – M.M Mar 27 '16 at 02:48
  • Please read [Is it a good idea to typedef pointers?](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers). – Jonathan Leffler Mar 27 '16 at 05:33

2 Answers2

1

The problem you're having is the casts

if((Vertex)aim.id ==(Vertex)vertex.id)

The function receives two void pointers

bool id_eq(void *aim, void *vertex);

Remember when working with structures the -> or . will be taken into account before the cast so this should be solved as following

if( ((Vertex)aim)->id ==((Vertex)vertex)->id)

I'd recommend the return as following, but that's personal taste:

bool id_eq(void *aim, void *vertex) {

    return ((Vertex)aim)->id  == ((Vertex)vertex)->id ? true:false;
}

Edit:

The "? true : false" is not necessary as the == will already result in a bool but it makes the code a little clearer.

Mr. Branch
  • 442
  • 2
  • 13
1

Change

if(*(Vertex)aim.id ==*(Vertex)vertex.id){

to

if((Vertex)aim->id == (Vertex)vertex->id){

or

if((*(Vertex)aim).id == (*(Vertex)vertex).id){

(Vertex) casts aim to "a pointer to a struct vertex_t". Then you can get the id of the struct vertex_t it points to by using the -> operator.

Also note that *(deference) has a lower procedure than . and ->.

nalzok
  • 14,965
  • 21
  • 72
  • 139
  • @AbbyMeng If you think this answer solves your problem, you can click the grey stick below the score to accept it. Of course, you can also upvote it if you want. – nalzok Mar 27 '16 at 03:48