About C ++, strlen (str) and sizeof (str)

First, we look for a test it

#include"stdio.h"

main(){
    char str[10] = "I am Limor宸";
    printf("%d %d",sizeof(str),strlen(str));
}

The resulting output is:

From the results we can see that sizeof (str) output is 10 and strlen result (str) output is 11 so why?

 Let's look at the difference between sizeof and strlen

  strlen when calculating the string length is '\ 0' for the end of the string flag.

  The actual size of the memory space occupied by an array of sizeof is classified to calculate the length.

If we look at a given allocation of space longer than the actual space of the case:

#include"stdio.h"

main(){
    char str[50] = "I am Limor宸";
    printf("%d %d",sizeof(str),strlen(str));
}

This time I gave this character array str initial allocation of 50 spaces, but only takes up 11 spaces.

 

The results are then calculated sizeof str string array 50 to the actual space occupied by

The result is calculated strlen 12, there is no space behind the calculations are not declared.

This shows that the array sizeof calculated amount of space, strlen length of the string is calculated and it '\ 0' closings also counted as a unit, but does not calculate null.

Guess you like

Origin www.cnblogs.com/LimorC/p/11208040.html