I want to know why I have a compilation error when I try this :
char *name = "some_string";
And with this I don't have any problem :
const char*name = "some_string";
or
char name[] = "some_string";
I want to know why I have a compilation error when I try this :
char *name = "some_string";
And with this I don't have any problem :
const char*name = "some_string";
or
char name[] = "some_string";
When you say
char *name = "some_string";
you are declaring a pointer to "some_string"
and pointers are used to point already existing data and the existing data here is "some_string"
which is placed under read only memory.
So const
keyword is important.
const char*name = "some_string";
// this is proper way
and modifying the "some_string"
after this declaration is illegal and causes undefined behavior
...
When you say char name[] = "some_string";
, "some_string"
will be placed under read only memory and the same is copied to name[]
array. later you can modify the content of name[]
.
For more info https://stackoverflow.com/a/18479996/1814023