搜尋此網誌

2025年3月4日星期二

Null terminator in C++

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;

}


In this example:

The string "Hello, world!" is automatically null-terminated by the compiler.

The array customStr is manually null-terminated by adding the character '\0' at the end.

The strlen function is used to calculate the length of the string up to, but not including, the null terminator.

Microsoft Copilot

沒有留言:

發佈留言