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)
}
CodePudding user response:
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'};
CodePudding user response:
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;
}