A Brief Overview of C-String & std::string


What is C-string ?


C-string is a one dimensional character array terminated by Null character.  To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Shirley."

#include <iostream>

using namespace std;

int main()
{
    char name[] = {'S', 'h', 'i', 'r', 'l', 'e', 'y', '\0'};
    
    cout << "Size of the char array[] or C-string is : " << sizeof(name)/sizeof(name[0]) <<endl;
    
    return 0;
}

Output:
1
Size of the char array[] or C-string is : 8

char name[8] = {'S', 'h', 'i', 'r', 'l', 'e', 'y', '\0'};

If you follow the rule of array initialisation then you can write the above statement as follows 

#include <iostream>

using namespace std;

int main()
{
    char name[] = "Shirley";
    
    /*
    //error: request for member ‘size’ in ‘name’, which is of non-class type ‘char [8]’
    cout << "Size of the name[] " << name.size() << endl;
    //error: request for member ‘length’ in ‘name’, which is of non-class type ‘char [8]’
    cout << "Length of the name[] " << name.length() << endl;
    */
    
    cout << "Size of the char array[] or C-string is : " << sizeof(name)/sizeof(name[0]) <<endl;
    
    return 0;
}

Output:
1
Size of the char array[] or C-string is : 8

I'm not sure how this has been accepted by the compiler.

#include <iostream>

using namespace std;

int main()
{
    char name[] = {'S', 'h', 'i', 'r', 'l', 'e', 'y'};
    
    cout << "Size of the char array[] or C-string is : " << sizeof(name)/sizeof(name[0]) <<endl;
    
    return 0;
}

Output:
1
Size of the char array[] or C-string is : 7


The below is the memory representation of the C-string 


Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array.

If you pass the C-string to a function, the size should be passed explicitly. Click here to know more.

Also, char */ char [] is a string in C whereas std::string is string in C++

For c, go with the string.h library functions. 

std::string in C++


For C++, don't go with C libraries like strcmp but compare. Click here to learn more.


Reference



Comments