Difference between string and char[] types in C++

C++Server Side ProgrammingProgramming

In this section we will see what are the differences between string and the char[] in C++. The char[] is basically an array of characters. So there are some properties of this array. These properties are listed below.

  • If the char[] is allocated in the stack section then it will always occupy 256 bytes of space. It will not depend on the size of the text.

  • If we use malloc() or calloc() to dynamically allocate space for it into the heap section then we are responsible for releasing the memory after using this, and we always have the overhead of a heap allocation.

  • If the size of the character array is larger than 256 characters, then the program may crash. It may generate ugly assertion message in our code.

  • To get the length of the string we have to scan the entire character array until we reach ‘\0’ character every time.

On the other hand, C++ has string into its standard namespace. This string is a class, and this contains character array inside it. It automatically manages for the user. In most of the cases the built-in array for string is 16 characters. So for shorter strings it does not fragment the string, but for larger string it uses the heap section.

C++ string has inbuilt ‘\0’ characters. It stores the length of the string without counting. As for shorter text is does not take heap then it protects from buffer overruns. And moreover the strings are easy to use in C++.

raja
Published on 01-Apr-2019 14:16:15
Advertisements