简体   繁体   中英

Understanding code of function strlen in C Programming

I was given a solution to the problem of recreating the function strlen in C Programming and it was the following, I need help understanding what the code is actually doing.

void    *ft_memset(void *b, int c, size_t len)
{
    size_t i;

    i = 0;
    while (i < len)
    {
        ((unsigned char *)b)[i] = c;
        i++;
    }
    return (b);
}

My biggest doubts are the meaning of ((unsigned char *)b)[i] = c , specially because I don't understand the ( *)b , and the need for a return b in a void function.

Thank you very much for your help, sorry if I did something wrong its my first post in stack overflow.

Let's break it down, albeit my C skills are somewhat rusty. Edits are welcome:)

void    *ft_memset(void *b, int c, size_t len)
{
    size_t i;

    i = 0;
    while (i < len)
    {
        ((unsigned char *)b)[i] = c;
        i++;
    }
    return (b);
}

First, you have declared a function called ft_memset which returns void * .

void * means a pointer to any object. It's just a number, pointing to a memory address. But we do not know what's in it because it's not properly annotated.

Your function takes three arguments: b which is a pointer to anything (or void pointer if you will) c which is an int 32-bit signed integer number. len which is a size_t which is usually an alias to an unsigned integer. Read more about size_t over here


Your function iterates through the first len bytes and sets the c 's value to those.

We're basically overwriting b 's contents for the first len bytes.


Now, what does ((unsigned char*)b) mean. This statement is casting your void * to an unsigned char* (byte pointer), this is just telling the compiler that we're gonna deal with the contents pointed by b as if they were just a unsigned char .

Later we're just indexing on the i -th position and setting the value c in it.

Understanding code of function strlen

void *ft_memset(void *b, int c, size_t len) is like void *memset(void *s, int c, size_t n) . They both assign values to the memory pointed to by b . These functions are quite different form strlen() .

size_t strlen(const char *s) does not alter the memory pointed to by s . It iterates through that memory looking for a null character .

size_t strlen(const char *s) {
  const char *end = s;
  while (*end != '\0') {
    end++;
  }
  return (size_t)(end - s); 
}

// or

size_t strlen(const char *s) {
  size_t i = 0;
  while (s[i] != '\0') {
    i++;
  }
  return i; 
}

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