In this code snippet
char *str="hello";
str[0]='H';
you are trying to change a string literal pointed to by the pointer str
. Any attempt to change a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
So though in C opposite to C++ string literals have types of non-constant arrays it is always better to declare pointers to string literals with the qualifier const
.
const char *str="hello";
You could declare a character array initialized by the string literal and change the array itself like
char str[] ="hello";
str[0]='H';