kamikaze_pilot
kamikaze_pilot

Reputation: 14834

c style string on c++ question

so you can do c style string on c++ using char * ...

my question is, can you pretty much do anything you can do on normal string with such declaration..

so suppose you have

char * c;

can you do:

c = "etcetc";
c = c + "dddddd";

etc?

and moreover is it pretty much interchangable with string?

so

char * c = "etcetc";
string s; 

s = c; 

would that be valid?

Upvotes: 0

Views: 377

Answers (5)

Eric Z
Eric Z

Reputation: 14505

A C-style string is essentially a NULL terminated character array while std::string in C++ is an well-designed object-oriented string class/object. In most case, they're NOT interchangeable and it depends on what operation you perform. You can always call std::string::c_str() to get the internal C-style string.

char * c

// OK because this makes c point to the starting address of "etcetc",
c = "etcetc";

// Compile-time error! You cannot add two pointers anyway because it's meaningless
c = c + "dddddd";

// OK, because string has constructor "string ( const char * s )"
string s1 = c;

string s2;
// OK, because string has "string& operator= ( const char* s )"
s2 = c;

One thing worth mentioning:

// "etcetc" is a constant string here and you cannot modify it via pointer c
char * c = "etcetc";

// You can change string contents in two cases
char c[] = "etcetc";
string str = "etcetc";

Upvotes: 3

mattnz
mattnz

Reputation: 516

I recently switched to C++ after years in Ada and C. I find I never use C style strings, except convert them to a string (and maybe back again if I have no choice). Do that, and a whole raft of common C problems disappears.

i.e. why char * x="dadada";when string x="dadada"; is much easier later in the code?

This is valid code and doed exactly what you expect because c is a string, not a char*.

string c ; 

.......

c = "etcetc";
c = c + "dddddd";

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67193

char* is a pointer to (address of) a char. When you say c = c + "xxx", you are adding the address of one string to another. This is almost certainly not what you want.

You'll need to use a string class that support concatenation to use the syntax you present. Otherwise, you can call old-style string functions like strcat().

Upvotes: 0

Phil Lello
Phil Lello

Reputation: 8639

Absolutely not, no.

(char *) is strictly a pointer to a memory location. String concatenation requires a new buffer with a copy of the source string (see strcat in your libC docs, for one method).

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

No, you can't concatenate char*s together using +; you have to use strcat and manually allocated buffers. That's why the std::string class exists in C++.

The assignment from char* to string is valid because the string class explicitly supports it.

Upvotes: 1

Related Questions