Sizeof() or strlen()?

Asked

Viewed 2,251 times

7

sizeof() or strlen()?

What’s the difference in their use on char hands? which is more appropriate?

2 answers

9


sizeof() returns the number of bytes of the complete string.

strlen() returns the number of characters of this string

When executing the code below:

#include <stdio.h>
#include <string.h>

int main()
{
    char c[10] = "str";
    printf("sizeof: %d, strlen: %d", sizeof(c), strlen(c));
    return 0;
}

The return is:

sizeof: 10, strlen: 3

That is: the string has 10 bytes allocated (c[10]), but you’re only using 3 characters ("str").

I hope I’ve cleared your doubt.

8

sizeof is a operator and returns the amount of bytes of an object or type. Not suitable to see the size of a string. If the string is represented by a pointer, the size will be of the pointer and not of the text. If it is by a array will always show a wrong result, at least because it will consider the null character of the text, it may be worse if the ending occurs before the last byte of the array, or it may be that the string has been allocated and has exceeded the limit of array.

Can’t confuse a array of char with a string. It seems to be the same thing, but it’s not.

strlen() is a function contained in string.h which accounts how many characters - which equate to bytes - in a string passed to it through a reference until it finds a null character \0. You mustn’t abuse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.