Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Comparing void pointers

  • 14-06-2010 07:21PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 Posts: 3,335 ✭✭✭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, Registered Users 2 Posts: 218 ✭✭Tillotson


    Works perfectly, makes sense too.

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


Advertisement