I know a technical definition (char*
is a pointer to a char
, which behaves similarly to an array
, and a string
(literal) is an array
of char
as it is), but how do they actually work? I read through the section on it (most of the tutorial really) on cplusplus.com (but I clearly have to re-read some sections). Still, I tried some practical examples and encountered some frustrating situations.
- I created a simple function,
void Log(std::string message) {std::cout << message << std::endl;}
, and that works great until I try to use it withchar*
in combination withstring
. For example, if I havestd::string a
andchar* b
, I cannot doLog(a + b)
, but I can dostd::string print = “”; print += a; print += b; Log(print);
Why? How should I define myLog(.)
function so that I can use it similarly toLog(a+b)
regardless of what types they are (at leaststd::string
andchar*
, but preferably alsoint
and other types)? If that’s possible, at least. - When I do
char * a = “some text”;
, I get the warningconversion from string literal to ‘char *’ is deprecated
. Obviously, this is not good, so why is this happening and how should I avoid this? - Under which circumstances should I prefer one over the other (apart from the obvious that I sometimes am forced because of some API’s, etc)? Is it a good practice, for example, to convert all my
char *
tostring
or vice-versa?
In general, my knowledge of char *
and strings
(and C++ in general) has… room for improvement, so feel free to give some sources for how to get more familiar and comfortable with char *
, strings
, and any other related types (arrays
, etc?). Although, I would very much appreciate it if someone would explain to me the two particular points above, as well.