Pointer and String constant
First, compare the two sections of code
Code 1
Char character [] = "hello"; * character = 'H'; // OK character [0] = 'H '; // OK printf ("% s \ r \ n", success );
Code 2
Char * CH2 = "world"; * CH2 = 'W'; // runtime error CH2 [0] = 'W '; // runtime error printf ("% s \ r \ n", CH2 );
Here"World"Is a String constant, and"Hello"No.
In code 2, * CH2 and CH2 [0] actually refer to 'w', while 'W' is a constant that cannot be modified!
Generally definedConst char * = "world ";Avoid the above running errors.
If you want to modify the string value, it should be defined as code 1! Or apply for a stack:
Char * s = (char *) malloc (sizeof (char) * 6); strcpy (S, "hello"); s [0] = 'H '; printf ("% s \ r \ n", S );
This "hello" is not a String constant, because it is applied on the stack, you can also use pointers to read and write!
Pointer and String constant