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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Comparing void pointers

  • 14-06-2010 7: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,323 ✭✭✭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