Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can you identify a string with a char pointer?

I am learning c++ from a book, but I am already familiar with programming in c# and python. I understand how you can create a char pointer and increment the memory address to get further pieces of a string (chars), but how can you get the length of a string with just a pointer to the first char of it like in below code?

Any insights would help!

String::String(const char * const pString)
{
     Length = strlen(pString)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This behavior is explained within the docs for std::strlen

std::size_t std::strlen(const char* str);

Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character. The behavior is undefined if there is no null character in the character array pointed to by str.

So it will count the number of characters up to, but not including, the '\0' character. If this character is not encountered within the allocated bounds of the character array, the behavior is undefined, and likely in practice will result in reading outside the bounds of the array. Note that a string literal will implicitly contain a null termination character, in other words:

"hello" -> {'h', 'e', 'l', 'l', 'o', '\0'};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading