char *name;
If I remember correctly (somebody correct me if not) C++ still _allows_
this as a special case, for backward compatibility with C.
"David" is a string literal which in the current C++ standard are of
type const char[].
In your code, you declare a pointer to a character and don't
initialize it. You then point the pointer to a string literal. The
compiler reserves memory for all string literals, and your code
shouldn't change this memory, which is what you're trying to do when
you change the 3rd character. Thus, IMHO, you really should do the
following. This really should be at least a compiler warning if you
don't declare it const.
const char * name = "David";
If you want a variable, of type char* that you can change, you need to
do the following.
char * name = new char[strlen("David") + 1];
strcpy(name,"David");
then, you can do this...
name[2] = 'X';
and you have to remember to do this at some point
delete [] name;
But "David" is a a constant, and you should never try to change a
constant.
Instead, do this:
#include <string>
...
std::string name = "David";
name[2] = 'D';
In this case "David" is copied into a variable, and you can change
the contents of variable.
Yes, you can do this, however there are times when you may not want to
use std::string, like in an embedded application. Thus, you need to
understand how C style string work as well.