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

29,625

Solution 1

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.

Solution 2

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!!

Share:
29,625

Related videos on Youtube

Teja
Author by

Teja

Updated on July 09, 2022

Comments

  • Teja
    Teja almost 2 years

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

    • strager
      strager almost 14 years
      Please define what you mean by "C string" and "C++ string". Both (especially the latter) are ambiguous.
    • paxdiablo
      paxdiablo almost 14 years
      @Gollum, that's probably an implementation issue. I don't think there's anything in the standard to say that C++ strings aren't allowed to be null-terminated. In fact, it may make c_str easier to implement.
    • Matt Joiner
      Matt Joiner almost 14 years
      I think generally they are nul terminated, to save on creating a temporary buffer when calling c_str()
    • user1703401
      user1703401
      I can't come up with something they might have in common. I'll have to sleep on that.
  • saolof
    saolof over 7 years
    This kind of behaviour from C is what causes bugs like Heartbleed.

Related