Why doesn't it work for me?

char p[4]={'h','g','y'}; cout<<strlen(p); 

This code prints 3.

 char p[3]={'h','g','y'}; cout<<strlen(p); 

Prints 8.

 char p[]={'h','g','y'}; cout<<strlen(p); 

This again prints 8.

Please help me as I cannot understand why three different values ​​are printed by resizing the array.

+6
c ++ string
source share
7 answers

strlen starts at the specified pointer and advances until the character '\0' reached. If your array does not have '\0' , it can be any number before reaching '\0' .

Another way to get the number you are looking for (in case you showed): int length = sizeof(p)/sizeof(*p); which will give you the length of the array. However, this is not strictly string length, as defined by strlen .

As @John Dibling mentions, the reason strlen gives the correct result in your first example is because you allocated space for 4 characters, but only used 3; the remaining 1 character is automatically initialized to 0, which corresponds to the character '\0' that strlen looking for.

+27
source share

Only your first example has a character set with a null terminating character - the other two examples do not have a null termination, so you cannot use strlen() on them in a specific order.

 char p[4]={'h','g','y'}; // p[3] is implicitly initialized to '\0' char p[3]={'h','g','y'}; // no room in p[] for a '\0' terminator char p[]={'h','g','y'}; // p[] implicitly sized to 3 - also no room for '\0' 

Note that in the latter case, if you used a string literal to initialize the array, you will get a null terminator:

 char p[]= "hgy"; // p[] has 4 elements, last one is '\0' 
+4
source share

This will give you a random number. strlen requires that lines be terminated with '\0 '.

+1
source share

try the following:

 char p[4]={'h','g','y', '\0'}; 
+1
source share

strlen is a standard library function that works with strings (in the sense of the term C). A string is defined as an array of char values ​​that ends with a value of \0 . If you supply something that is not a string in strlen, the behavior is undefined: code may crash, the code may lead to meaningless results, etc.

In your examples, only the first one contains a strlen string, so it works as expected. In the second and third cases, what you supply is not a string (does not end with \0 ), so the results are not expected to make sense.

+1
source share

'\0' terminate your char buffer.

 char p[4]={'h','g','y', '\0'}; 
0
source share

This is because strlen () expects to find a null terminator for the string. In this case, you do not have it, so strlen () continues to count until it finds \ 0 or receives a memory access violation and your program dies. Rip!

0
source share

All Articles