Just When I Though I Understood Pointers

Just When I thought I understood pointers I run across this example:

1
2
3
4
5
 int main(){
     char *s = "hello world";
     *s = 'H';
return 0;
 }


Why does this crash?
Last edited on
"hello world"; will return a position in constant memory so you can't modify it, the proper way of declaring 's' should be this:
const char *s = "hello world";
If you want something you can modify you should mace 's' an array: char s[] = "hello world"; or, of course, a std::string
Last edited on
Thanks for the reply!! I am just beginning.

The code snippet was an example I ran across, nothing I am actually trying to use.

But other programs that I am practicing with declare pointers and explicitly change the values.
You can change values with pointers, you just need to own the memory you want to modify.
Some compilers may also allow the program you posted but that isn't a standard behaviour.
So, how do you know if you own the mem?
You can allocate memory:
1
2
3
4
5
char *c;
c = new char[6];
sprintf(c,"hello");
*c='H';
delete[] c;


Or you can just use arrays
Topic archived. No new replies allowed.