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 *
?
Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.
NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of '*'(asterik) is also same. 2. char *const ptr : This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by ptr.
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With