Sizeof () or strlen ()?

5

sizeof() or strlen()?

What's the difference between using them in char pointers? which is more appropriate?

    
asked by anonymous 29.07.2016 / 20:23

2 answers

6

sizeof() returns the number of bytes in the entire string.

strlen() returns the number of characters in this String

Running 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 is only using 3 characters ( "str" ).

I hope to have clarified your doubt.

    
29.07.2016 / 20:28
6

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

You can not confuse a array of char with a string . It seems to be the same thing, but it is not.

strlen() is a function contained in string.h that counts how many characters - which equals bytes - in a sequence passed to it through a reference until it finds a null character %code% .

    
29.07.2016 / 20:40