Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the difference between C strings and C++ strings?

Tags:

whats the difference between C Strings and C++ strings. Specially while doing dynamic memory allocation

like image 884
Teja Avatar asked Aug 11 '10 02:08

Teja


People also ask

Is there any difference between C style string and C++ strings?

You can (if you need one) always construct a C string out of a std::string by using the c_str() method. Show activity on this post. C++ strings are much safer,easier,and they support different string manipulation functions like append,find,copy,concatenation etc.

Are C-strings faster?

C-strings are usually faster, because they do not call malloc/new.

Should I use C-string or string?

Use string. cstring is so 1970's. string is a modern way to represent strings in c++. you'll need to learn cstring because you will run into code that uses it.

What are C-strings used for?

Strings are used for storing text/characters. For example, "Hello World" is a string of characters. Unlike many other programming languages, C does not have a String type to easily create string variables.


2 Answers

I hardly know where to begin :-)

In C, strings are just char arrays which, by convention, end with a NUL byte. In terms of dynamic memory management, you can simply malloc the space for them (including the extra byte). Memory management when modifying strings is your responsibility:

char *s = strdup ("Hello");
char *s2 = malloc (strlen (s) + 6);
strcpy (s2, s);
strcat (s2, ", Pax");
free (s);
s = s2;

In C++, strings (std::string) are objects with all the associated automated memory management and control which makes them a lot safer and easier to use, especially for the novice. For dynamic allocation, use something like:

std::string s = "Hello";
s += ", Pax";

I know which I'd prefer to use, the latter. You can (if you need one) always construct a C string out of a std::string by using the c_str() method.

like image 98
paxdiablo Avatar answered Sep 24 '22 05:09

paxdiablo


C++ strings are much safer,easier,and they support different string manipulation functions like append,find,copy,concatenation etc.

one interesting difference between c string and c++ string is illustrated through following example

#include <iostream>                            
using namespace std;

int main() {
    char a[6]; //c string
    a[5]='y';
    a[3]='o';
    a[2]='b';
    cout<<a; 
    return 0;
}

output »¿boRy¤£f·Pi»¿

#include <iostream> 
using namespace std; 
int main() 
{ 
  string a; //c++ string
  a.resize(6);
  a[5]='y';
  a[3]='o';
  a[2]='b';
  cout<<a;
  return 0;
}

output boy

I hope you got the point!!

like image 35
Chandan Singh Avatar answered Sep 23 '22 05:09

Chandan Singh