Monday, 16 November 2009

C String and C++ Strings: Similarities and Differences

I came across this scenario recently when a C style string (as some people refer to char[] as) had to be compared to a C++ string and even though this is straightforward, i fell in the same trap as a lot of people about forgetting that there is a Nul charachter as the end of C style string. Anyway, here is an example to demonstrate both the strings.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate length and size of char* and string
//and to show similarity and difference between them
#include<iostream>

using namespace
std;

int
main()
{

cout<<endl;
char
a[10]="Hello";
cout<<"Size of a = "<<sizeof(a)<<endl;
a[5]='\0'; //Terminating the C string in between with Nul character
cout<<"Size of a = "<<sizeof(a)<<endl;

cout<<endl;
char
b[]="Hello";
cout<<"Size of b = "<<sizeof(b)<<endl; //Note the size
//Automatic Nul charachter added

cout<<endl;
string c("Hello");
cout<<"Size of c = "<<sizeof(c)<<endl;
cout<<"Length of c = "<<c.length()<<endl;

c += " Zahid";
cout<<"Size of modified c = "<<sizeof(c)<<endl;
cout<<"Length of modified c = "<<c.length()<<endl;

//Add an extra NULL charachter
cout<<endl;
char
d[]="Hello\0";
cout<<"Size of d = "<<sizeof(d)<<endl;
for
(int i = 0; i < sizeof(d); i++)
{

cout<<"d["<<i<<"] = "<<d[i]<<endl;
}


//When is a char[] similar to string?
cout<<endl;
char
e[]="Zahid";
string f = "Zahid\0";
const
char* temp = f.c_str();
if
(strcmp(e , temp) == 0)
{

cout<<"e == f"<<endl;
}

else

{

cout<<"e != f"<<endl;
}


return
0;
}







The output is as follows:

No comments:

Post a Comment