char p[4]={'h','g','y'};
cout<<strlen(p);
This code prints 3.
char p[3]={'h','g','y'};
cout<<strlen(p);
This prints 8.
char p[]={'h','g','y'};
cout<<strlen(p);
This again prints 8.
Please help me as I can’t figure out why three different values are printed by changing the size of the array.
strlenstarts at the given pointer and advances until it reaches the character'\0'. If you don’t have a'\0'in your array, it could be any number until a'\0'is reached.Another way to reach the number you’re looking for (in the case you’ve shown) is by using:
int length = sizeof(p)/sizeof(*p);, which will give you the length of the array. However, that is not strictly the string length as defined bystrlen.As @John Dibling mentions, the reason that
strlengives the correct result on your first example is that you’ve allocated space for 4 characters, but only used 3; the remaining 1 character is automatically initialized to 0, which is exactly the'\0'character thatstrlenlooks for.