简体   繁体   中英

Can someone explain me this code? What does it mean (unsigned char)c? and ft_strlen((char *)s)?

When declaring some variables, what is meant with parenthesis. Also * and & symbols with parenthesis make confusion here. Please explain this code.

#include "libft.h"    
char    *ft_strrchr(const char *s, int c)
{
    int     len;
    char    ch;

    ch = (unsigned char)c;
    len = ft_strlen((char *)s);
    if (ch == '\0')
        return ((char *)(&s[len]));
    while (--len >= 0)
    {
        if (s[len] == ch)
            return ((char *)(&s[len]));
    }
    return (NULL);
}

The brackets (type)variable cast the variable to a different type.

& just before the variable gets the memory address of that variable.

So, for example:

int x = 1;

char *ptr = (char *)&x; // gets the address and because it is int *, we cast it to char *
/* the above is significant, because usually int is 4 bytes and char is 1 byte, so
 * incrementing a pointer, we can go to the next byte's address if we are using a 1 byte type
 * or, it jumps 4 bytes if we are usinig int pointer. This is a reason why this is sometimes used
 * on memcpy, so that memcpy can copy all bytes to the destination
 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM