userX
userX

Reputation: 390

What is the EXACT technical difference between "const char *" and "const string"

I need a deep technical explanation of what I'm about to ask, not a solution.

Ive been learning pointers for a week now, I understand it pretty well. But while writing a program, I stumbled upon this error:

cannot convert ‘const std::string’ to ‘const char*’ for argument ‘2’ to ‘char* strcpy(char*, const char*)’

So I solved pretty easily with string.c_str() no problem. But I got very interested into why this is. I have been searching like crazy why a const string is not the same a const char *. When people explain a string they say its no different than a char *, so why does adding a const before the string not make it a const char *?

Upvotes: 9

Views: 9243

Answers (1)

user541686
user541686

Reputation: 210352

string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string).

A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information. Therefore, in order for you to be able to deduce the length of a "string" represented by a char*, you must terminate it with something special, which is conventionally the null character '\0' in C.

But a string doesn't terminate itself with '\0' (it's extra work for no benefit), so the question becomes: what if you need to convert between the two formats?

Converting from a char* to a string can happen implicitly -- string has a constructor just for that purpose. But to go the other way around, you have to tell the string object to null-terminate itself and give you a valid pointer for your purpose. (It won't do that implicitly because it can require extra work and/or lead to accidents in code.)

Upvotes: 13

Related Questions