In C++, a null terminator is a special character used to signify the end of a string. It is represented by the character '\0' (also known as the null character). When a string is stored in memory, the null terminator is added at the end to indicate where the string terminates. This is particularly important for functions that process strings, as they rely on the null terminator to know when to stop reading the string.
Here’s an example to illustrate:
#include <iostream>
#include <cstring>
int main() {
char str[] = "Hello, world!";
std::cout << "Length of the string: " << strlen(str) << std::endl; // Output: 13
// Manually adding a null terminator
char customStr[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
std::cout << "Custom string: " << customStr << std::endl; // Output: Hello
std::cout << "Length of the custom string: " << strlen(customStr) << std::endl; // Output: 5
return 0;
}
沒有留言:
發佈留言