0

I'm trying to reproduce the function memcmp, and when i try to compile i got the error:

error: assignment makes integer from pointer without a cast [-Werror]
str1 = (unsigned char*)s1

Here is my code :

int ft_memcmp(const void *s1, const void *s2, size_t n)
{
    unsigned char   str1;
    unsigned char   str2;

    str1 = (unsigned char*)s1;
    str2 = (unsigned char*)s2;
    while (n--)
    {
        if (str1 != str2)
           return (str1 - str2);
        str1++;
        str2++;
    }
    return (0);
}

can anyone help me with those cast ? i really don't understand why it doesn't work

Paul Roub
  • 36,322
  • 27
  • 84
  • 93

1 Answers1

3

You want str1 and str2 to be pointers (matching the cast), not unsigned chars:

unsigned char *str1, *str2;

str1 = (unsigned char*)s1;
str2 = (unsigned char*)s2;

while (n--)
{
  if (*str1 != *str2)
    return (*str1 - *str2);

  str1++;
  str2++;
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • I would use ++str1 and ++str2, it should be faster. – IFeelGood Nov 10 '14 at 16:06
  • 3
    @IFeelGood Why on earth would that be faster? I can't imagine a compiler turning bare `str1++;` and `++str1;` into even slightly different code. – Paul Roub Nov 10 '14 at 16:08
  • post-increment usually involves keeping a copy of the previous value around and adds a little extra code. Pre-increment simply does it's job and gets out of the way. I think is good to know that... – IFeelGood Nov 10 '14 at 16:09
  • 3
    It's also good to spend 10 or 15 minutes reading up on compiler optimization, then ask yourself why a compiler would "usually" keep old values around in the case at hand. The [answer you copied-and-pasted](http://stackoverflow.com/questions/2020184/preincrement-faster-than-postincrement-in-c-true-if-yes-why-is-it#answer-2020205) is relevant in some cases, but almost certainly not here. – Paul Roub Nov 10 '14 at 16:17
  • Yes i copied and paste for short (I had no time to rewrite it) and yes in this case "probably" the speed doesn't change but you can't be sure what the compiler does until you don't see the ASM code and I think is good for a programmer usually use ++something instead of something++ because it can be faster. But if this makes you unconfortable you can keep going in writing str1++ instead ++str1 but as you saw in older post where I copiead and paste that's could be slower... – IFeelGood Nov 10 '14 at 16:26