2

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)
}

Vexea
  • 167
  • 1
  • 1
  • 8
  • 2
    C-style strings are [null-terminated](https://en.wikipedia.org/wiki/Null-terminated_string). `strlen` scans until it finds a `'\0'` and then stops. – Nathan Pierson Dec 10 '21 at 14:20
  • 2
    *How can you identify a string with a char pointer?* -- You can't. What happens is that `strlen` just trusts that what you are giving it is null-terminated, and counts/increments until a null is hit. It knows nothing else. – PaulMcKenzie Dec 10 '21 at 14:22
  • I think there are answers in these comments.... And the question seems worthy to get an answer post. – Yunnosch Dec 10 '21 at 14:23
  • Does this answer your question? [How does the strlen function work internally?](https://stackoverflow.com/questions/4132849/how-does-the-strlen-function-work-internally) – Nathan Pierson Dec 10 '21 at 14:34

2 Answers2

4

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'};
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

You can implement your own method in C-style like:

size_t get_length(const char * str) {
  const char * tmp = str;
  while(*str++) ;
  return str - tmp - 1;
}
yemo
  • 145
  • 8