recently i learn the pointer of c. wrote a programme below
1 #include<stdio.h>
5 char *s = "Hello world!";
You are not creating a new string object here. The string literal "Hello
world!" is created at compile time and integrated into the program's
run-time image. It is effectively a piece of the program.
Consequently, this assignment to s[0] constitutes self-modifying code:
your program is trying to change itself.
It is somewhat like trying to do 3 = 4.
This doesn't have any standard-defined behavior.
It cannot work for programs that are stored in ROM, including their string
literals. If you run this on some embedded systems, it might run without a
diagnostic, but the write to the ROM has no effect. On some other systems, you
might get a "bus error" from the invalid access.
Many modern operating systems mimic the situation of a program being placed
into ROM. They load programs into memory, and then use the virtual memory
hardware to mark the memory write-protected.
If you want a modifiable static character array, you have to define an array object.
static char a[] = "hello";
char *s = a; /* perhaps unnecessary; just use a in place of s */
Also note that different occurences of "Hello world!" are not necessarily
distinct objects.
Given these definitions
char *s1 = "hello", *s2 = "hello", *s3 = "lo";
It's quite possible that s1 == s2, and that s3 == s1 + 3. If that is
the case and the run-time lets you successfully execute this:
s1[3] = 'f'
then s1 changes to "helfo", s2 changes to "helfo" and s3 changes to "fo".
This kind of thing can lead to surprising differences in behavior when someone
port the program to another kind of computer, or just another kind of compiler,
or even just changes some code generation options on the same compiler. In
other words, it is highly non-portable.