While using C++ , we are often considerate about which type to be used for strings. In this post we will check the difference between these two.Below is the implementation of two types in question

//Using string #include<iostream> #include<string> using namespace std; int main() { string str; cout<<"Enter the address"; getline(cin, str); cout<<"My Address:"<<str; return 0; } // Using Char Array #include<iostream> using namespace std; int main() { char str[128]; cout<<"Enter Address"; getline(cin, str); cout<<"My address:"<<str; return 0; }

Lets see first char array implementation:

Char array(char str[128]) when allocated on stack will occupy 128 bytes no matter if the input str size is less than 128.

when allocated on heap using malloc or new operator , programmer is responsible for releasing the memory.

when copied more than the size of str(128) then it might crash .

To Calculate the str length entire string has to scanned for ‘\0’.

std::string

A string is a class that contains a char array, but automatically manages it for you.

C++ strings can contain embedded \0 characters.

std:string can know their length without counting.

std::string are faster than heap allocated char arrays for short texts and protect you from buffer overruns

If you have any suggestion or feedback to add. Please leave a comment.