Replacing characters in C++ Pointer Character string? -


suppose have in c++:

char *p = "apple"; 

i can't this:

p[1] = 'w'; 

but why can this?

p = "orangetorange"; 

as p points constant string literal if do: p[1] = 'w'; trying modifying string literal read constant , illegal operation (undefined behavior).

whereas in expression p = "orangetorange"; modify value of p variable pointer char. , assigning new address value p valid operation, p start pointing new string literal.

to add further, suppose if p points array p[1] = 'w'; not invalid operation consider below example code:

char str[] = "apple"; char* p = str; // p points array  p[1] = 'w';    // valid expression, not str[1] = 'w' valid.  p = "orangetorange";   // valid // str = "orangetorange"; not valid `str` not pointer array name 

here both operations asked valid!

note: 2 declarations char *str , char str[] different. understand read: what sizeof(&arr) return?


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -