What is a null-terminated string in C/C++?

C++Server Side ProgrammingProgramming

In C the strings are basically array of characters. In C++ the std::string is an advancement of that array. There are some additional features with the traditional character array. The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by ‘\0’). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.

The size of the string may smaller than the array size, but if there are some null character inside that array, that will be treated as the end of that string.

See the following example. Here we have defined one string using std::string, then we will provide the same string, but there will be one \0 inside it.

Example

#include<iostream>
using namespace std;
main() {
   string my_string = "This is a sample text";
   cout << my_string << endl;
   my_string = "This is a sam\0ple text"; //check the \0
   cout << my_string;
}

Output

This is a sample text
This is a sam
raja
Published on 07-May-2019 11:41:51

Advertisements