Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Comparing void pointers

Options
  • 14-06-2010 8:21pm
    #1
    Registered Users Posts: 218 ✭✭


    I want to find if the two values are equal, here's what I've done so far which compares byte by byte:
     21 int cmp_void (void *a, void *b, size_t sz) {
     22         size_t i;
     23         for (i = 0; i < sz; i++) {
     24                 if (*(char *)(a + i) != *(char *)(b + i)) {
     25                         return 0;
     26                 }
     27         }
     28         return 1;
     29 }
    
    Seems to work but I'm wondering if there is a better way which doesn't throw compiler warnings.
    mylist.c:24: warning: pointer of type 'void *' used in arithmetic
    
    thanks


Comments

  • Registered Users Posts: 3,287 ✭✭✭padraig_f


    I think the warning is because you've tried to do arithmetic on a void* pointer. when you do arithmetic on pointers, the compiler takes into account the type of the pointer. so a+1 where was an int pointer would add on 4 bytes, a+1 where a was a short pointer would add on two bytes. this is why the compiler complains when you do arithmetic with a void pointer, how many bytes does it add on?

    I think if you cast the void*s to char* before doing the addition, it will get rid of the warning.

    also, if you're allowed use the standard library, there's a function memcmp.


  • Registered Users Posts: 218 ✭✭Tillotson


    Works perfectly, makes sense too.

    Personal project, I just don't know the libraries yet.


Advertisement