char* p = "Hello"; //BAD - OBSOLETE!
strcpy (p,"bye");
A good compiler should give your warning (or error) on the first line, because that is made obsolete and the language requires you to write that as:
char const * p = "Hello"; //GOOD
Once you write this (which is correct way to write this, anyway), then everything becomes clear : p
points to const data, means the data which p
points to cannot be modified, that in turns implies, you cannot overwrite it using strcpy
(or manually).
If you want to overwrite this, one way to declare p
as array:
char p[] = "Hello"; //OK
strcpy (p,"bye"); //OK - for any string (2nd arg) of length <= 5
In C++, you should use std::string
, avoiding char*
and char[]
as much as possible. So a C++ way to write code would be this:
#include <string> //must include this first
std::string p = "Hello";
p = "bye"; //overwrite it.
So simple!